2

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.

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);
    }
}
Aleksandr Erokhin
  • 1,904
  • 3
  • 17
  • 32
VSK
  • 250
  • 4
  • 13
  • So what confuses you exactly? – Aleksandr Erokhin Oct 03 '15 at 21:44
  • @AlexErohin, static variable belongs to a class and in my case it belongs to super class and I can access that variable in sub class also. How can it be? any valid reasons. My Initial thought was, only I can access super class instance variable and methods in sub class. – VSK Oct 04 '15 at 04:04
  • Please, take a look at this thread: http://stackoverflow.com/a/9898144/4745608 – Aleksandr Erokhin Oct 04 '15 at 14:06
  • @AlexErohin, Understood.Thanks for sharing the above link. – VSK Oct 06 '15 at 12:17

2 Answers2

3

You can access it using the subclass object.superClassStaticField or 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 {}
blacktide
  • 10,654
  • 8
  • 33
  • 53
mantiq
  • 129
  • 7
1

Static variables are class variables, you can access them using 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);
    }
}
blacktide
  • 10,654
  • 8
  • 33
  • 53
Gaurav
  • 44
  • 3