在抽象类中使用main方法

在抽象类中使用main方法

问题描述:

我知道在抽象类中使用main方法是合法的,因为Eclipse允许我执行以下操作并将该类作为java应用程序运行。但做这样的事情是否有意义?

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?

是否存在真实世界场景,需要在抽象类中使用main方法?

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");
    }
}

打印出来

c:\Users\ndh>java A
starting main in A
A

预期但很无聊,

c:\Users\ndh>java B
starting main in A   
A        

它没有做你想要的。

阴影静态方法调用不像虚拟覆盖实例方法那样工作,你必须从明确命名为用作查找正确方法签名的起点的类(或默认情况下,您将获得进行调用的类)。问题是main方法无法知道子类(或者将它放在抽象类上的意义),因此没有好的方法可以将子类特定的信息引入超类main方法。

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.

我的首选是最小化我对static关键字的使用,保留它用于常量(尽管枚举结果不是很多)和没有依赖关系的无状态函数。而是支持面向对象的技术。使用静态方法,您必须具体。有了OO的想法是你可以避免具体,让子类自己处理。

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.