Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing inherited class variables in java

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?

like image 782
user1058210 Avatar asked Jan 06 '12 19:01

user1058210


2 Answers

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);
    }
}
like image 113
ollins Avatar answered Oct 02 '22 11:10

ollins


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.

like image 24
Mike Samuel Avatar answered Oct 02 '22 11:10

Mike Samuel