Is the main method inherited?

Is the public static void main method on the superclass inherited by subclasses? Yes, it can be accessed by all subclasses directly. So it is possible to have a main method just on the superclass, and be able to run each subclass that doesn't itself declare the main method. For example:
public class Main {
public static void main(String[] args) {
System.out.println("In Main.main(String[])");

public class Main2 extends Main {
public void m2() {
main(null); //access the main method in superclass

public class Main3 extends Main2 {}
Running Main, Main2, Main3 have the same effect:
C:\tmp> java Main
In Main.main(String[])

C:\tmp> java Main2
In Main.main(String[])

C:\tmp> java Main3
In Main.main(String[])
When running Main2 and Main3 inside NetBeans 6.1 beta, I got the error Class "Main2" does not have a main method. Note this error is not from java runtime. It seems NetBeans is doing some validation and being too restrictive.


root said...

neither in eclipse

Rani said...

running d java Main in d above example gives a class not found exception....however java Main2 and java Main 3 displays statement written in System.out.println of Main class.........(confused)

Steve Smith said...

Great and Useful Article.

Online Java Training

Java Online Training India

Java Online Course

Java EE course

Java EE training

Best Recommended books for Spring framework

Java Interview Questions

Java Course in Chennai

Java Online Training India