且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在抽象类中使用main方法

更新时间:2023-10-06 14:08:40

否, 并不是的。尝试创建一个类层次结构,其中不同的类共享相同的主方法似乎没有用。请参阅此示例:

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.