How To Prevent Method Overriding In Java?

How To Prevent Method Overriding In Java?

There Different ways to prevent method overriding in java,In That first way is To prevent a specific method from being overridden in a subclass, use the final modifier on the method declaration, which means "this is the final implementation of this method".That Means if You apply final modifier to parent class method ,this can,t be overridden in subclass(child class).so check the below sample code

Example: Prevent Method Overriding In Java using final modifier


package com.java2study;

public class ParentClass {
public final void parentMethod(){
System.out.println("iam parent class final method");
}

}

public class ChildClass extends ParentClass {
public void parentMethod(){
System.out.println("parent class final method not being overridden");

}

public static void main(String[] args) {
ChildClass c = new ChildClass();

c.parentMethod();

}

}


output


Exception in thread "main" java.lang.VerifyError: class com.java2study.ChildClass overrides final method parentMethod.()V
at java.lang.ClassLoader.defineClass1(Native Method)

The Second Way is we cannot ovrerride the Super( Parent) class private methods.That Means if any parent class method is declared with private method then we cannot ovverride that method in Sub(child) class.here Remember one point private access specifier means it self it will not visible in sub classes. so private methods cannot visible in child classes.check the below code

Example: Prevent Method Overriding In Java using private modifier


package com.java2study;

public class ParentClass {
private void parentMethod(){
System.out.println("iam parent class private method");
}

}

public class ChildClass extends ParentClass {


public static void main(String[] args) {
ChildClass c = new ChildClass();

c.parentMethod();

}

}

output


Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method parentMethod() from the type ParentClass is not visible

at com.java2study.ChildClass.main(ChildClass.java:9)

The Third Way is We are Not allowed override super class static method as non-static method in subclass.Lets see sample code

Example: Prevent Method Overriding In Java using static modifier


package com.java2study;

public class ParentClass {

public static void parentMethod(){
System.out.println("iam parent class static method");
}

}

public class ChildClass extends ParentClass {

public void parentMethod(){
System.out.println("sub class non static method");
}
public static void main(String[] args) {
ChildClass c = new ChildClass();

c.parentMethod();

}

}

output


Exception in thread "main" java.lang.Error: Unresolved compilation problem:
This instance method cannot override the static method from ParentClass

at com.java2study.ChildClass.parentMethod(ChildClass.java:5)
at com.java2study.ChildClass.main(ChildClass.java:11)

Here Point you cannot ovverride Private,final,static methods in java

-->