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);
    }
}
4
  • So what confuses you exactly? Commented Oct 3, 2015 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. Commented Oct 4, 2015 at 4:04
  • Please, take a look at this thread: stackoverflow.com/a/9898144/4745608 Commented Oct 4, 2015 at 14:06
  • @AlexErohin, Understood.Thanks for sharing the above link. Commented Oct 6, 2015 at 12:17

2 Answers 2

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 {}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.