本文共 3134 字,大约阅读时间需要 10 分钟。
As we know that inheritance enables us to reuse existing code, sometimes we do need to set limitations on extensibility for various reasons; the final keyword allows us to do exactly that.
If you make any variable as final, you cannot change the value of a final variable(It will be constant).
Example of final variable The below diagram demonstrates that the final variable name can’t be reassigned which will result in compile time error.The final keyword may be applied to a method, indicating the method may not be overridden in any subclass.
When we design a class and feel that a method shouldn’t be overridden, we can make this method final. We can also find many final methods in Java core libraries.
Sometimes we don’t need to prohibit a class extension entirely, but only prevent overriding of some methods. A good example of this is the Thread class. It’s legal to extend it and thus create a custom thread class. But its isAlive() methods is final.
The below diagram demonstrates that the final method can’t be overridden which will result in compile time error:
Java final class
The final keyword may be applied to a class, indicating the class may not be extended (subclassed). If we look at the code of Java core libraries, we’ll find many final classes there. For example String, Wrapper classes and BigDecimal, BigInteger etc. Java final class example The below diagram demonstrates that the final class can’t be extended which will result in compile time error.What is blank or uninitialized final variable?
A final variable that is not initialized at the time of declaration is known an as a blank final variable. If you want to create a variable that is initialized at the time of creating an object and once initialized may not be changed, it is useful. For example PAN CARD number of an employee. It can be initialized only in the constructor.class Student{ int id; String name; final String PAN_CARD_NUMBER; ... }
Note that the final PAN_CARD_NUMBER variable not initialized. We can initialize a blank final variable only in a constructor.
转载地址:http://vbgrn.baihongyu.com/