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.
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 astatic
method in the superclass, then the method in the subclass hides the one in the superclass.