Search code examples
javagetter-setter

How can access to a private variable in another class by using a getter function?


First class(The parent class)

package revisionOOP;
public class Myclass {
    private int x;
    public void changeThis() {
        x = 10;
        System.out.println("x = " + x);
    }
    //getter
    public int UnprivateX() {
        return this.x;
    }
    public static void main(String[] args) {
        Myclass inst = new Myclass();
        inst.changeThis();
    }
}

The other class(The child class)

package revisionOOP;
public class MySecondClass extends Myclass {
    static int y;
    public void changeExThis() {
        y = 20;
        System.out.println("x = " + inst.UnprivateX());
        //I want to get the private x value from Myclass class  ,How ?
        System.out.println("y = " + y);
    }
    public static void main(String[] args) {
        MySecondClass inst = new MySecondClass();
        Myclass inst2 = new Myclass();
        inst2.changeThis();
        inst.changeThis();
        inst.changeExThis();
    }
}

How can access to a private variable in another class by using a getter function ? And how can i change it in the child class ?


Solution

  • You can use method in child like this

    public void changeExThis() {
        y = 20;
        System.out.println("x = " + UnprivateX());
        System.out.println("y = " + y);
    }
    

    Also you can use this.UnprivateX() or super.UnprivateX()