Inheritance is a substantial rule of any Object-Oriented Programming (OOP) language but still, there are ways to prevent method overriding in child classes which are as follows:
Methods:
- Using a static method
- Using private access modifier
- Using default access modifier
- Using the final keyword method
Method 1: Using a static method
This is the first way of preventing method overriding in the child class. If you make any method static then it becomes a class method and not an object method and hence it is not allowed to be overridden as they are resolved at compilation time and overridden methods are resolved at runtime.
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
Base base = new Child();
base.hello();
}
}
class Base {
public static void hello()
{
System.out.println( "Hello from base class" );
}
}
class Child extends Base {
public static void hello()
{
System.out.println( "Hello from child class" );
}
}
|
OutputHello from base class
Method 2 Using private access modifier
Making any method private reduces the scope of that method to class only which means absolutely no one outside the class can reference that method.
Example
Java
import java.io.*;
public class GFG {
public static void main(String[] args)
{
Child child = new Child();
child.hello();
}
}
class Child extends Base {
public void hello()
{
System.out.println( "Hello from child class" );
}
}
class Base {
private void hello()
{
System.out.println( "Hello from base class" );
}
}
|
OutputHello from child class
Method 3 Using default access modifier
This can only be used when the method overriding is allowed within the same package but not outside the package. Default modifier allows the method to be visible only within the package so any child class outside the same package can never override it.
Example
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
Base base = new Child();
base.hello();
}
}
class Base {
private void hello()
{
System.out.println( "Hello from base class" );
}
}
class Child extends Base {
void hello()
{
System.out.println( "Hello from child class" );
}
}
|
Output:

Method 4: Using the final keyword method
The final way of preventing overriding is by using the final keyword in your method. The final keyword puts a stop to being an inheritance. Hence, if a method is made final it will be considered final implementation and no other class can override the behavior.
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
Child child = new Child();
child.hello();
}
}
class Child extends Base {
public void hello()
{
System.out.println( "Hello from child class" );
}
}
class Base {
public final void hello()
{
System.out.println( "Hello from base class" );
}
}
|
Output:
