9

Ok just for sake knowledge , I tried below cases (Assume that Class A and B are in same package)

ClassA

public class ClassA {

  public static void main(String[] args) {
     System.out.println("A");
  }
}

ClassB

public class ClassB extends ClassA {

  public static void main(String[] args) {
    System.out.println("B");
  }
}

executing above ClassB it will produce output of B now after below change in classB

ClassB

public class ClassB extends ClassA {
   //blank body
}

If I compile and run in terminal it gives me output A that was totally surprising as it should had given NoSuchMethodError as no main method was their so kindly explain the weird behavior ?

Note: Many answers contains Override word please use hiding as we cannot override static methods in java.

akash
  • 22,664
  • 11
  • 59
  • 87
Bhargav Modi
  • 2,605
  • 3
  • 29
  • 49
  • 1
    There is no `static` method overriding, but there is **hiding**. In the first case, `ClassB` hides the `main` method from `ClassA`. In the second case `ClassB` does not hide the `main` method so the one from `ClassA` is called. – Boris the Spider Apr 06 '15 at 13:12

3 Answers3

7

In the first case, you're hiding the main method since you're defining a new one in the subclass, in the second case you didn't you'll inherent A's main.

See The Java™ Tutorials - Overriding and Hiding:

If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass.

Maroun
  • 94,125
  • 30
  • 188
  • 241
2

In Java subclasses inherit all methods of their base classes, including their static methods.

Defining an instance method in the subclass with the matching name and parameters of a method in the superclass is an override. Doing the same thing for static methods hides the method of the superclass.

Hiding does not mean that the method disappears, though: both methods remain callable with the appropriate syntax. In your first example everything is clear: both A and B have their own main; calling A.main() prints A, while calling B.main() prints B.

In your second example, calling B.main() is also allowed. Since main is inherited from A, the result is printing A.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

public static void main(String[] args) is just a method which you inherit from A in second case.

Saif
  • 6,804
  • 8
  • 40
  • 61