Reputation: 2655
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.
Upvotes: 9
Views: 417
Reputation: 726539
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
.
Upvotes: 2
Reputation: 7042
public static void main(String[] args)
is just a method which you inherit from A
in second case.
Upvotes: 0
Reputation: 95958
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.
Upvotes: 7