[英]Access superclass static variable in subclass
I have a superclass Test
with a static variable a
and I've also created a subclass Test1
from which I am able to access superclass static variable. 我有一个带有静态变量a
的超类Test
,并且我还创建了一个子类Test1
,从中我可以访问超类静态变量。
Is this a valid way to do so? 这是这样做的有效方法吗? Any explanation is highly appreciated. 高度赞赏任何解释。
public class Test {
public static String a = "";
Test() {
a += "testadd";
}
}
public class Test1 extends Test {
public Test1() {
a += "test1add";
}
public static void main(String args[]){
Test1 test1 = new Test1();
System.out.println(a);
}
}
Static variables are class variables, you can access them using classname.variablename. 静态变量是类变量,您可以使用classname.variablename访问它们。
public class Test {
public static String a = "";
Test() {
a += "testadd";
}
}
public class Test1 extends Test {
public Test1() {
Test.a += "test1add";
}
public static void main(String args[]) {
Test1 test1 = new Test1();
System.out.println(a);
}
}
You can access it using the subclass object.superClassStaticField
or SuperClassName.superClassStaticField
. 您可以使用subclass object.superClassStaticField
或SuperClassName.superClassStaticField
对其进行访问。 Latter is the static way to access a static variable. 后一种是访问静态变量的静态方法。
For example: 例如:
public class SuperClassStaticVariable {
public static void main(String[] args) {
B b = new B();
b.a = 2; // works but compiler warning that it should be accessed as static way
A.a = 2; // ok
}
}
class A {
static int a;
}
class B extends A {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.