【问题标题】:Access superclass static variable in subclass访问子类中的超类静态变量
【发布时间】:2015-10-03 15:55:51
【问题描述】:

我有一个超类 Test 和一个静态变量 a,我还创建了一个子类 Test1,我可以从中访问超类静态变量。

这是一种有效的方法吗?任何解释都非常感谢。

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

【问题讨论】:

  • 那么到底是什么让你感到困惑?
  • @AlexErohin,静态变量属于一个类,在我的情况下它属于超类,我也可以在子类中访问该变量。怎么可能?任何正当理由。我最初的想法是,只有我可以访问超类实例变量和子类中的方法。
  • @AlexErohin,了解。感谢分享上述链接。

标签: java inheritance


【解决方案1】:

您可以使用subclass object.superClassStaticFieldSuperClassName.superClassStaticField 访问它。后者是访问静态变量的静态方式。

例如:

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 {}

【讨论】:

    【解决方案2】:

    静态变量是类变量,您可以使用 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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-22
      • 2012-04-09
      • 2022-01-05
      • 2011-03-05
      相关资源
      最近更新 更多