The Wayback Machine - https://web.archive.org/web/20240810084338/https://www.geeksforgeeks.org/different-ways-to-prevent-method-overriding-in-java/
Open In App

Different Ways to Prevent Method Overriding in Java

Last Updated : 10 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

  1. Using a static method
  2. Using private access modifier
  3. Using default access modifier
  4. 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




// Java Program to Prevent Method Overriding
// using a static method
 
// Importing java input output classes
import java.io.*;
 
// Class 1
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an object og Base class
        Base base = new Child();
 
        // Printing message from base class as
        // its static methods have static binding
 
        // Hence even if the object is of Child class
        //  message printed is from base class
        base.hello();
    }
}
 
// Class 2
// Parent class
class Base {
 
    // hello() method of parent class
    public static void hello()
    {
 
        // Print and display the message if
        // hello() method of parent class is called
        System.out.println("Hello from base class");
    }
}
 
// Class 3
// Child class
class Child extends Base {
 
    // Overriding the existing method - hello()
    // @Override
    // hello() method of child class
    public static void hello()
    {
        // Print and display the message if
        // hello() method of child class is called
        System.out.println("Hello from child class");
    }
}


Output

Hello 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




// Java Program to Prevent Method Overriding
// using a private method specifier
 
// Importing input output classes
import java.io.*;
 
// Class 1
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an object of Child class
        Child child = new Child();
 
        // Calling hello() method in main()
        child.hello();
    }
}
 
// Class 2
// Helper class 1
// Child Class
class Child extends Base {
 
    //@Override
    // hello() method of child class
    public void hello()
    {
 
        // Print statement when hello() method of
        // child class is called
        System.out.println("Hello from child class");
    }
}
 
// Class 3
// Helper class 2
// Parent Class
class Base {
 
    // hello() method of parent class
    private void hello()
    {
 
        // Print statement when hello() method of
        // child class is called
        System.out.println("Hello from base class");
    }
}


Output

Hello 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




// Java Program to Prevent Method Overriding
// using a private method specifier
 
// Importing input output classes
import java.io.*;
 
// Class 1
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an object of base class
        Base base = new Child();
 
        // Calling hello() method using Base class object
        base.hello();
    }
}
 
// Class 2
// Parent class
class Base {
 
    // hello() method of parent class
    private void hello()
    {
 
        // Print statement when hello() method of
        // child class is called
        System.out.println("Hello from base class");
    }
}
 
// Class 3
// Child class
class Child extends Base {
 
    // Overriding existing method
    // @Override
 
    // Hello method of child class
    void hello()
    {
 
        // Print statement when hello() method
        // of child class is called
        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




// Java Program to Prevent Method Overriding
// using a final keyword method
 
// Importing input output classes
import java.io.*;
 
// Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating object of Child class
        Child child = new Child();
 
        // Calling hello() method using Child class object
        child.hello();
    }
}
 
// Class 2
// Child class
class Child extends Base {
 
    // Overriding
    // @Override
 
    // Method of child class
    public void hello()
    {
        // Print statement for Child class
        System.out.println("Hello from child class");
    }
}
 
// Class 3
// Base class
class Base {
 
    // Method of parent class
    public final void hello()
    {
        // Print statement for Base(parent) class
        System.out.println("Hello from base class");
    }
}


Output:



Similar Reads

When We Need to Prevent Method Overriding in Java ?
Here we will be discussing why should we prevent method overriding in java. So, before going into the topic, let's give a look at the below important concept then we will move to the actual topic. As we know Object Oriented Programming (OOPs) concept consists of 4 important concepts that are as follows: EncapsulationInheritancePolymorphismAbstracti
4 min read
Overriding methods from different packages in Java
Prerequisite : Overriding in Java, Packages in Java Packages provide more layer of encapsulation for classes. Thus, visibility of a method in different packages is different from that in the same package. How JVM find which method to call? When we run a java program, JVM checks the runtime class of the object. JVM checks whether the object's runtim
3 min read
Difference Between Method Overloading and Method Overriding in Java
The differences between Method Overloading and Method Overriding in Java are as follows: Method Overloading Method Overriding Method overloading is a compile-time polymorphism.Method overriding is a run-time polymorphism.Method overloading helps to increase the readability of the program.Method overriding is used to grant the specific implementatio
4 min read
Exception Handling with Method Overriding in Java
An Exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run-time, that disrupts the normal flow of the program’s instructions. Exception handling is used to handle runtime errors. It helps to maintain the normal flow of the program. In any object-oriented programming language, Overriding is a feature t
6 min read
Java - Covariant Method Overriding with Examples
The covariant method overriding approach, implemented in Java 5, helps to remove the client-side typecasting by enabling you to return a subtype of the overridden method's actual return type. Covariant Method overriding means that when overriding a method in the child class, the return type may vary. Before java 5 it was not allowed to override any
4 min read
Overriding equals method in Java
Consider the following Java program: Java Code class Complex { private double re, im; public Complex(double re, double im) { this.re = re; this.im = im; } } // Driver class to test the Complex class public class Main { public static void main(String[] args) { Complex c1 = new Complex(10, 15); Complex c2 = new Complex(10, 15); if (c1 == c2) { System
3 min read
Overriding toString() Method in Java
Java being object-oriented only deals with classes and objects so do if we do require any computation we use the help of object/s corresponding to the class. It is the most frequent method of Java been used to get a string representation of an object. Now you must be wondering that till now they were not using the same but getting string representa
3 min read
Variables in Java Do Not Follow Polymorphism and Overriding
Variables in Java do not follow polymorphism. Overriding is only applicable to methods but not to variables. In Java, if the child and parent class both have a variable with the same name, Child class's variable hides the parent class's variable, even if their types are different. This concept is known as Variable Hiding. In the case of method over
2 min read
Overriding in Java
In Java, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, the same parameters or signature, and the same return type(or sub-type) as a method in its super-class, then th
13 min read
Output of Java program | Set 18 (Overriding)
Prerequisite - Overriding in Java 1) What is the output of the following program? class Derived { protected final void getDetails() { System.out.println("Derived class"); } } public class Test extends Derived { protected final void getDetails() { System.out.println("Test class"); } public static void main(String[] args) { Derive
3 min read
Practice Tags :
three90RightbarBannerImg