java基础---->final关键字的使用

时间:2023-03-09 00:15:22
java基础---->final关键字的使用

  这里介绍一些java基础关于final的使用,文字说明部分摘自java语言规范。心甘情愿这四个字,透着一股卑微,但也有藏不住的勇敢。

Final关键字的说明

一、关于final变量规范说明

、A  final variable may only be assigned to once.
、Once a final variable has been assigned, it always contains the same value.
、If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object.
、A variable of primitive type or type String , that is final and initialized with a compile-time constant expression, is called a constant variable.

二、关于final类的规范说明

、A class can be declared  final if its definition is complete and no subclasses are desired or required.
、It is a compile-time error if the name of a final class appears in the extends clause of another class declaration; this implies that a final class cannot have any subclasses.
、It is a compile-time error if a class is declared both final and abstract , because the implementation of such a class could never be completed.
、Because a final class never has any subclasses, the methods of a final class are never overridden.

三、关于final学习的测试代码如下

  • final变量的代码测试:
/**
* Created by huhx on 2017-05-12.
*/
public class FinalFiledTest {
final String string = "hello world";
final Map<String, String> map = new HashMap<>(); public static void main(String[] args) {
FinalFiledTest finalTest = new FinalFiledTest();
// finalTest.string = "world hello"; // cannot assign a value to final variable "string"
finalTest.map.put("username", "linux");
Map<String, String> map2 = new HashMap<>();
// finalTest.map = map2; // cannot assign a value to final variable "map"
System.out.println(finalTest.map.get("username"));
}
}
  • final方法的代码测试:
/**
* Created by huhx on 2017-05-12.
*/
public class FinalMethodTest {
public static void main(String[] args) {
Women women = new Women();
// women.username; // 没有权限使用
women.sayWorld();
// women.sayHuhx(); // 没有权限调用
}
} class People {
private String username;
String address; People() {
this.username = "huhx";
this.address = "china";
} public void sayHello() {
System.out.println("Hello");
} public final void sayWorld() {
System.out.println("World");
} private void sayHuhx() {
System.out.println("Huhx");
}
} class Women extends People {
// 不能重写父类的final方法,但是可以在子类中使用
// public void sayWorld() {
// System.out.println("World");
// }
}
  • final类的代码测试:
/**
* Created by huhx on 2017-05-12.
*/
// cnanot inherit from final "com.linux.huhx.finalTest.Person"
//public class FinalClassTest extends Person{
//
//} final class Person {
private String username; public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
}
} // modifier "final" not allowed here, 接口不能用final修饰
//final interface Human {
//
//}

友情链接