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.
If your program doesn't contain the main method, then you will get an error “main method not found in the class”. It will give an error (byte code verification error because in it's byte code, main is not there) not an exception because the program has not run yet.
Here you have to run the class "Main" instead of the class you created at the start of the program. To do so pls go to Run Configuration and search for this class name"Main" which is having the main method inside this(public static void main(String args[])). And you will get your output.
The main method is not needed in java programs. As others have pointed out, web applications do not use the main method.
The main() method is static so that JVM can invoke it without instantiating the class. This also saves the unnecessary wastage of memory which would have been used by the object declared only for calling the main() method by the JVM.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With