Sometimes we don’t want
other classes to inherit our class or
overwrite methods which we defined in our class or
change the value of variable from our class and this is where “final” keyword comes in picture.
We can declare
class,
method and
variable
using final keyword.
final class
* Once we declare class with final key word, we make sure the no othre class will inherit it.
* Java itself uses final keyword in predefine classes like “Math” class.
* When we declare class with final keyword then it is not possible for other class to overwrite any methods from our class.
Example:
final class FinalDemo { public void disp() { System.out.println("n ITVoyagers Final Class Demo"); } } /* class ChildClass extends FinalDemo { } */ class FinalClass { public static void main(String[] args) { FinalDemo fd = new FinalDemo(); fs.disp(); } }Output:
ITVoyagers Final Class Demo
final method
* If we don’t want other class to overwrite some of our methods, then we have to declare those methods using final keyword.
class FinalDemo { public final void disp() // final method { System.out.println("n ITVoyagers final method Demo"); } public void show() { System.out.println("n Arthor : ITVoyagers"); } } class ChildClass extends FinalDemo { public void show() { System.out.println("n Arthor : ITVoyagers n Visit : itvoyagers.in"); } /* public final void disp() // this method can't be overwritten because it is declared using final keyword { System.out.println("n ITVoyagers final method Demo"); } */ } class FinalClass { public static void main(String[] args) { ChildClass cc = new ChildClass(); cc.disp(); cc.show(); } }Output:
ITVoyagers Final Class Demo Arthor : ITVoyagers Visit : itvoyagers.in
final variable
* Once we declare any variable using final keyword then it make sure that no other class can change its value.
* If we declare instance variable with final keyword it states that this instance variable can’t be assign to another object.
class FinalDemo { public final String fvar = "Arthor : ITVoyagers Visit : itvoyagers.in"; } class FinalClass { public static void main(String[] args) { FinalDemo fd= new FinalDemo(); //fd.fvar = "ITVoyagers"; // it will throw an error because fvar variable is declared using final keyword. System.out.println(fd.fvar); } }Output:
Arthor : ITVoyagers Visit : itvoyagers.in