Method Hiding

Method Hiding in Java

Method hiding in Java occurs when a subclass defines a static method with the same name and signature as a static method in its superclass. It is different from method overriding because the choice of which method to invoke is based on the declared type of the object at compile-time, not the actual type at runtime.

Example 1: Animal Hierarchy

Consider the following hierarchy of animal classes:

    
      class Animal {
          public static void info() {
              System.out.println("Animal class");
          }
      }
      
      class Dog extends Animal {
          public static void info() {
              System.out.println("Dog class");
          }
      }
    
  

In this example, the Animal class has a static method named info. The Dog class extends the Animal class and defines its own static method with the same name info. When we invoke the info method using a reference of type Animal, it prints "Animal class" because the method is resolved at compile-time based on the declared type.

    
      Animal animal = new Animal();
      Animal.info(); // Output: Animal class
      
      animal = new Dog();
      animal.info(); // Output: Animal class
    
  

Example 2: Vehicle Hierarchy

Consider another example where we have a hierarchy of vehicle classes:

    
      class Vehicle {
          public static void info() {
              System.out.println("Vehicle class");
          }
      }
      
      class Car extends Vehicle {
          public static void info() {
              System.out.println("Car class");
          }
      }
    
  

In this case, the Vehicle class has a static method named info. The Car class extends the Vehicle class and defines its own static method with the same name info. When we invoke the info method using a reference of type Car, it prints "Car class" because the method is resolved at compile-time based on the declared type.

    
      Vehicle vehicle = new Vehicle();
      Vehicle.info(); // Output: Vehicle class
      
      vehicle = new Car();
      vehicle.info(); // Output: Vehicle class
    
  

Go To OOPS Page Click Here

Post a Comment

Previous Post Next Post