12

If you inherit from an activity where certain member variables were declared, how do you access these member variables in the subclass executing the inheritance?

1
  • Also check that you don't have a naming conflict: java.sys-con.com/node/46344 if you're running into unexpected behavior Commented Jan 6, 2012 at 19:26

4 Answers 4

9

public or protected member names can be accessed via this.memberName from any constructor or non-static method or initializer.

private or package level members (accessed from a subclass in a different package) cannot be accessed directly and will need to be accessed via an unprivileged interface such as a public getter.

Sign up to request clarification or add additional context in comments.

Comments

7
class A {
    protected int a = 3;
}

class B extends A {
    protected int b = 2;

    void doIt() {
        System.out.println("super.a:" + super.a);
        System.out.println("this.b: " + this.b);
    }
}

4 Comments

You don't need the super keyword.
That's right. But this is a beginner question. So, I want to make it absolutely clear.
You would only need the super keyword if the field was hidden by a field in the subclass.
Also right :) . But I don't want explain the abbreviations. If user1058210 goes this way, everything will be fine... and at some day he will find the shorter solution.
3

If the members were declared private, or if they were declared with default (package) access and your subclass is in a different class, you cannot access the variables. If accessors were provided, you can use those. Otherwise, they are not accessible.

If the members were declared protected or public, then you access them as if they were declared in your own class (this.var, or just var if there's no ambiguity). If you have a member in the subclass with the same name as the superclass, you can use super.var to access the superclass variable.

Comments

1

As stated by others, public and protected fields can be accessed via this.field from the subclass. Package-private fields can also be accessed in the same way, but only if the subclass is in the same package as the parent.

Private fields cannot be accessed in this way, but they can be accessed using Java reflection, if the security settings permit it. It's generally not recommended practice (private members are usually private for a reason), but it can be useful in some situations, for example accessing private class members for code testing purposes. See the answers to this question for how to use reflection in this way.

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.