Различные способы предотвращения переопределения методов в Java

Опубликовано: 29 Января, 2022

Наследование является важным правилом любого языка объектно-ориентированного программирования (ООП), но, тем не менее, существуют следующие способы предотвратить переопределение методов в дочерних классах:

Методы:

  1. Использование статического метода
  2. Использование модификатора частного доступа
  3. Использование модификатора доступа по умолчанию
  4. Использование метода последнего ключевого слова

Метод 1: использование статического метода

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