I know it's legal to have a main method in an abstract class, because Eclipse allows me to do the following and run the class as a java application. But does it make sense to do something like this?
Is there a real world scenario where one would need to have a main method in an abstract class?
public abstract class Automobile
{
public Boolean powerOn()
{
// generic implementation for powering on an automobile
return true;
}
public void move()
{
// generic implementation for move
}
public void changeDirection(String newDir)
{
// generic implementation for changing direction
}
public abstract void accelerate(Integer changeInSpeed);
public abstract Integer refuel(Integer inputFuel);
public static void main(String[] args)
{
System.out.println("I am a main method inside an abstract Automobile class");
}
}
No, not really. Trying to create a class hierarchy where different classes share the same main method doesn't seem useful. See this example:
public abstract class A {
public static void doStuff() {
System.out.println("A");
}
public static void main(String[] args) {
System.out.println("starting main in A");
doStuff();
}
}
class B extends A {
public static void doStuff() {
System.out.println("B");
}
}
this prints out
c:\Users\ndh>java A
starting main in A
A
which is expected but boring, and
c:\Users\ndh>java B
starting main in A
A
which doesn't do what you want.
Shadowing static method calls doesn't work like virtual overriding of instance methods, you have to start with explicitly naming the class to use as your starting point for finding the right method signature (or by default you get the class where the call is made). The problem is that the main method can't know about the subclasses (or what's the point of putting it on the abstract class), so there's no good way to get subclass-specific information into the superclass main method.
My preference is to minimize my use of the static keyword, reserving it for constants (although not so much since enums came out) and stateless functions with no dependencies. Favor object-oriented techniques instead. With static methods you have to be specific. With OO the idea is you can avoid being specific and let the subclasses take care of themselves.