Font Awesome Icons

Tutorial

final keyword in Java

The final keyword in java is used to restrict the user. final keyword can be used along with variables, methods and classes.

 

final variable

final variables are nothing but constants. We cannot change the value of a final variable once it is initialized.

 

public class Adhar

{  

final int uid=99;    

void myMethod()

{         

uid=101;    

}      

public static void main(String args[])

{        

Adhar obj=new  Adhar ();         

obj.myMethod();      

}   

}

final method

A final method cannot be overridden. Which means even though a subclass can call the final method of parent class without any issues but it cannot override it

 

class Parent

{  

final  void show()

{      

System.out.println(“Parent’s show()”);      

}

}  

class Child extends Parent

{         

void show()     

{     

System.out.println(“Child’s show()”);     

}

}

 public class Main

{    

public static void main(String[] args)    

{                 

Child c = new Child();        

c.show();    

}

}

 

final class

We cannot extend a final class.

 

final class XYZ

{  

}         

class ABC extends XYZ

{     

void demo()

{      

System.out.println(“My Method”);   

}     

public static void main(String args[])

{        

ABC obj= new ABC();       

       obj.demo();   

}  

}