can method of subclass access private variables of superclass code example

Example: can method of subclass access private variables of superclass

public class Base {

    private int x;  // field is private

    protected int getX() {  // define getter
        return x;
    }

    protected void setX(int x) {  // define setter
        this.x = x;
    }
}
//Then you would use it in your child class like this:
class Child extends Base{

    void foo() {
        int x = getX(); // we can access the method since it is protected.
        setX(42);  // this works too.
    }
}

Tags:

Java Example