Final Keyword in Java

The final is a keyword in Java Programming language which is used to restrict the access for some component, It can be used 3 places in Java language such as

[su_list icon=”icon: arrow-circle-o-right”]

  • final variable
  • final method
  • final class

[/su_list]

Final Variable

Once the variable is declared as final variable the value cannot be changed once its assigned, and final modifier can be declared as local variable.

Example

package com.javatraineronline;

public class FinalVariable {

	public static void main(String[] args) {
	
		final int a = 10; // the variable value is assigned as 10 it cannot be changed.
		
		a = 20; // This will throw the compailation error.
	}
}

Final Method

The method can be declared as a final, Which cannot be ovverridden in the sub classes. Whatever implementation is available in base class that cannot be ovverridden in sub classes.

Example

package com.javatraineronline;

public class BaseClass {

	// final public or public final both are possible sysntax in Java
	
	public final void doSomething(){ //final method
	
		System.out.println("Some Activities...."); // Base class implementation
	}
}
package com.javatraineronline;

public class ChildClass extends BaseClass {

	// trying to override 
	// It cannot be ovverridden its <strong>final method</strong> you will get compailation error
	public void doSomething() { 
	
		System.out.println(""); 
	}
}

Final Class

In Java final keyword can be used to make the class as final. Once class is declared as final class it cannot be inherited in other word in no child classes can extends the final class.

Example

package com.javatraineronline;

// final public class or public final class both sysntax are possible in Java
public final class BaseClass {

	
}
package com.javatraineronline;

// It will give the compailation error stating final class cannot be inherited
public class ChildClass extends BaseClass { // it won`t work

	
}

Note: Hi friends, If you are looking One to One Online Java Tutor don`t hesitate to contact me. I am Online Java Tutor have been helping many students and professionals across the globe to gain more knowledge on the Java, J2EE, Spring, Hibernate, Struts, AKKA, UI and other frameworks by providing Online Java Training. you can call or whatsapp to +91 9941937705 anytime to reach me.