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?
-
Also check that you don't have a naming conflict: http://java.sys-con.com/node/46344 if you're running into unexpected behavior – jefflunt Jan 06 '12 at 19:26
4 Answers
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.

- 118,113
- 30
- 216
- 245
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);
}
}

- 1,851
- 12
- 16
-
1
-
4That's right. But this is a beginner question. So, I want to make it absolutely clear. – ollins Jan 06 '12 at 19:33
-
3You would only need the `super` keyword if the field was hidden by a field in the subclass. – Ted Hopp Jan 06 '12 at 19:38
-
1Also 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. – ollins Jan 06 '12 at 19:48
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.

- 232,168
- 48
- 399
- 521
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.