CodesJava

Easy learning with example program codes

what is final method in java


A method declared with final keyword is known as final method.

Example

/**
 * This program is used to show that final method can't be override.
 * @author CodesJava
 */
class Show{
	public final void show(){
		System.out.println("Hello world.");
	}
}
 
class Display extends Show{
	//error because final method can't be override.
	public void show(){
		System.out.println("Hello codesjava.com.");
	}
}
 
public class FinalExample2 {
	public static void main(String args[]){
		//creating object of Display class
		Display obj = new Display();
		//method call
		obj.show();
	}
}

Output

Exception in thread "main" java.lang.VerifyError: 
class com.codesjava.business.Display overrides final method show.()V
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at com.codesjava.business.FinalExample2.main
(FinalExample2.java:23)

Note: A final method can be inherited but can’t be override.

Java interview questions on final keyword



Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap