Java Final Keyword


In Java language, the final is the keyword. The final can apply to the variable, method, and class.

Syntax:

final 

Final Variable

A final variable can't able to change. It is a constant variable.


Example:-

 class B 
{
	final int a=5;// final varibale
	void showdata()
    {	
    	// a=9; It can't change the value of a. It throw compile error. 
    	System.out.println("Derived class a value: "+ a);
    }
}
public class Finalvariable
{  
	public static void main(String args[])
    {  
	    B b= new B();
        b.showdata();
	}   
}

Example:-

To invoke the base class method using super keyword.

 class A
{
	int a=10;
    final void showdata() // final method
    {
    	System.out.println("Base class a value: "+ a);
    }
}
class B extends A{
	int a=5;
	void showdata()
    {
    	System.out.println("Derived class a value: "+ a);
    }
}
public class Finalmethod
{  
	public static void main(String args[])
    {  
	    B b= new B();
        b.showdata();
	}   
}

Final Class

A final class can't able to extend the class.


Example:-

To invoke the base class constructor using super keyword.

final class A // final class
{
	int a=10;
    A()
    {
    	System.out.println("Base class a value: "+ a);
    }
}
class B extends A{
	int a=5;
	B()
    {
    	System.out.println("Derived class a value: "+ a);
    }
}
public class Finalclass
{  
	public static void main(String args[])
    {  
	    B b= new B();
	}   
} 



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.