简体   繁体   English

如何使用 getter 函数访问另一个类中的私有变量?

[英]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 ?如何使用 getter 函数访问另一个类中的私有变量? And how can i change it in the child class ?我如何在子类中更改它?

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()你也可以使用this.UnprivateX()super.UnprivateX()

First of all, you should declare all fields of class as private, then create getters and setters for each one and they have to have names start with getFieldName & setFieldName.首先,您应该将类​​的所有字段声明为私有,然后为每个字段创建 getter 和 setter,它们的名称必须以 getFieldName 和 setFieldName 开头。 and should be public.并且应该是公开的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 面向对象的编程,getter不会从另一个类获取私有变量 - Object oriented programming, getter is not getting private variable from another class 如何使用Java访问另一个类的私有字段中的私有字段 - How to access a private field in a private field in another class using Java 我们如何使用getter和setter访问私有实例变量? - How we are able to access private instance variable with getter and setter? 从另一个类访问私有变量? - Access private variable from another class? 如何获得对父类的私有变量的访问权限? - How can I gain access to a parent class's private variable? 如何使用 lombok SuperBuilder 访问超级 class 的私有变量 - How to access private variable of super class by using lombok SuperBuilder 子类对象如何访问父类的私有变量,就像java中一样,除了类本身可以访问私有变量之外,否? - How does the subclass object access the private variable of super class,as in java no except the class itself can access the private variable? 如何访问另一个类中的函数? - How can I access a function in another class? .valueOf使用另一个类的私有变量 - .valueOf using another class's private variable 如何在另一个类的函数中访问一个类的变量? - How do I access a variable of one class in the function of another class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM