您的位置:首页 > 其它

新手笔记:使用final关键字修饰

2016-03-22 17:00 375 查看
final关键字可以修饰:
变量
参数
方法

final关键字修饰变量
final修饰的变量即可看作常量,即 不可变得变量

package fianlTest;

public class Test
{
/**
* @param args
*/
public static void main ( String[ ] args )
{
final String str = "hello "; // 常量
String result1 = str + "world";

String str1 = "hello "; // 变量
String result2 = str1 + "world";

String demo = "hello world";

System.out.println( result1 == demo );
System.out.println( result2 == demo );
}
} 输出结果为:
true
false 当final变量是基本数据类型以及String类型时,如果在编译期间能知道它的确切值,则编译器会把它当做编译期常量使用。也就是说在用到该final变量的地方,相当于直接访问的这个常量,不需要在运行时确定。由于变量str被final修饰,因此会被当做编译器常量,所以在使用到的地方会直接将变量替换为它的值。而对于变量str1的访问却需要在运行时通过链接来进行。但是相对的:
package fianlTest;

public class Test
{
/**
* @param args
*/
public static void main ( String[ ] args )
{
final String str = getStr( ); // 常量
String result1 = str + "world";
// final String str = "hello "; // 常量
// String temp = "world";
// String result1 = str + temp;

String str1 = "hello "; // 变量
String result2 = str1 + "world";

String demo = "hello world";

System.out.println( result1 == demo );
System.out.println( result2 == demo );
}
public static String getStr ( )
{
return "hello ";
}
}

显示的结果为:
false
false

final关键字修饰参数
使用final关键字修饰的参数,只能在方法中使用,而不能修改
final关键字修饰方法
使用final关键字修饰的方法,不能被重写。
final关键字修饰类
使用final关键字修饰的类,不能被继承。
final修饰引用变量时,虽然变量不可变,但是内部的属性变量可以改变。
package fianlTest;

public class Test
{
/**
* @param args
*/
public static void main ( String[ ] args )
{
final MyClass myClass = new MyClass( );
System.out.println( ++ myClass.num );
}
}

package fianlTest;

public class MyClass
{
public int num = 1;
}
显示结果为:

2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: