问题是在Java中为什么我不能定义一个抽象的静态方法?例如
abstract class foo {
abstract void bar( ); // <-- this is ok
abstract static void bar2(); //<-- this isn't why?
}
Run Code Online (Sandbox Code Playgroud) 我刚开始用一个例子来解释它:
public abstract class A{
static String str;
}
public class B extends A{
public B(){
str = "123";
}
}
public class C extends A{
public C(){
str = "abc";
}
}
public class Main{
public static void main(String[] args){
A b = new B();
A c = new C();
System.out.println("b.str = " + b.str);
System.out.println("c.str = " + c.str);
}
}
Run Code Online (Sandbox Code Playgroud)
这将打印出来:
b.str = abc
c.str = abc
但我想要一个解决方案,其中实例化超类的每个子类都有自己的类变量,同时我希望能够通过标识符引用该类变量,或者在抽象超类中定义的方法调用.
所以我希望输出为:
b.str = 123
c.str = abc …