final :
Disadvantages of inheritance: It breaks the encapsulation of the code. The emergence of final just makes up for this disadvantage.
final keyword:
1-final is a modifier that can modify classes, methods, and variables;
2-Final modified classes cannot be inherited
3-Final modified methods cannot be overridden
The variable modified by 4-final is a constant, which can only be assigned once and must be assigned a certain value when it is defined.
rule :
Constants that are defined as final are represented by capital letters, and each word is separated by an underscore _.
Example one:
class Father01{
final String FATHER01_NAME = "Zhang San";
final int FATHER01_AGE = 20;
final void show(){
// age=9; //Error!!! age is defined as final, it has been assigned a value when it was defined, and cannot be assigned again.
System.out.println("Name: " + FATHER01_NAME);
}
}
final class Father02{
}
class Son01 extends Father01{
// public void show() { //Error!!! Methods defined by final cannot be overridden
//
// }
}
//class Son02 extends Father02{ //Error!!! Classes defined by final cannot be inherited
//
//}