gpt4 book ai didi

java - 有一个主要的抽象类?

转载 作者:搜寻专家 更新时间:2023-11-01 01:51:27 24 4
gpt4 key购买 nike

将 main 用于抽象类通常是一种不好的做法,还是由于抽象类能够拥有主体的性质而被允许?

最佳答案

当然,抽象类可以有一个 main 方法,就像任何类都可以有一个 main 方法一样,事实上,这是测试抽象类的一种方法——如果您在 main 方法中创建它的具体实现。抽象类唯一不能做的就是按原样构造它们,而不扩展它们和实现所有抽象方法。

public abstract class Foo {
public abstract void bar();

public static void main(String[] args) {
// anonymous inner class representation
Foo foo = new Foo() {
// must implement all abstract methods
public void bar() {
System.out.println("bar");
}
};
foo.bar();
}
}

编辑:VitalyGreck 的要点:

abstract classes are abstract because they don't implement some methods in their body. having bar() implemented inside the main() method (even static) confuses users of your class. Good practice is to make two separate classes, one of them - abstract, another - with implementation and static method enclosed. Or dynamically find the enclosing class (see stackoverflow.com/questions/936684/…) using reflection.

换句话说,仅仅因为它可以完成,并不意味着它应该完成。

关于java - 有一个主要的抽象类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29501553/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com