Can we override the main method in java?

Java 8Object Oriented ProgrammingProgramming

Overriding is one of the mechanisms to achieve polymorphism. This is the case when we have two classes where one inherits the properties of another using the extends keyword and, these two classes have the same method including parameters and return type (say, sample()).

Since it is an inheritance. If we instantiate the subclass a copy of superclass’s members is created in the subclass object and, thus both methods are available to the subclass (object).

When we invoke this method (sample) JVM calls the respective method based on the object used to call the method.

Example

 Live Demo

class Super{
   public static void sample(){
      System.out.println("Method of the superclass");
   }
}
public class OverridingExample extends Super {
   public static void sample(){
      System.out.println("Method of the subclass");
   }
   public static void main(String args[]){
      Super obj1 = (Super) new OverridingExample();
      OverridingExample obj2 = new OverridingExample();
      obj1.sample();
      obj2.sample();
   }
}

Output

Method of the superclass
Method of the subclass

Overriding Static methods

When superclass and subclass contain the same method including parameters and if they are static. The method in the superclass will be hidden by the one that is in the subclass.

This mechanism is known as method hiding in short, though super and subclasses have methods with the same signature if they are static, it is not considered as overriding.

Overriding main method

You cannot override static methods and since the public static void main() method is static we cannot override it.

Example

 Live Demo

class Super{
   public static void main(String args[]) {
      System.out.println("This is the main method of the superclass");
   }
}
class Sub extends Super{
   public static void main(String args[]) {
      System.out.println("This is the main method of the subclass");
   }
}
public class MainOverridingExample{
   public static void main(String args[]) {
      MainOverridingExample obj = new MainOverridingExample();
      Super.main(args);
      Sub.main(args);
   }
}

Output

This is the main method of the superclass
This is the main method of the subclass
raja
Published on 03-Jul-2019 15:50:29
Advertisements