Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/400.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 子类如何更改父类实例变量的值_Java - Fatal编程技术网

Java 子类如何更改父类实例变量的值

Java 子类如何更改父类实例变量的值,java,Java,子类如何更改父类实例变量的值。我曾尝试在子类中使用super.variable name,但当我打印parent.variable name时,我可以看到更改没有反映在父变量中。使用parent更新父类的变量。variable在OOP上是一个错误的想法。当您扩展父类时,就像您的子类与父类成为一体一样,它们不再分离,所以从现在开始,就像变量是子类的一样。但是仅仅是切片的区别是publicprivate定义,它设置了类的每个项的可见性。因此,在下面的示例中,我刚刚为父级定义了一个私有变量,这样子级就

子类如何更改父类实例变量的值。我曾尝试在子类中使用super.variable name,但当我打印parent.variable name时,我可以看到更改没有反映在父变量中。

使用
parent更新父类的变量。variable
在OOP上是一个错误的想法。当您扩展父类时,就像您的子类与父类成为一体一样,它们不再分离,所以从现在开始,就像变量是子类的一样。但是仅仅是切片的区别是
public
private
定义,它设置了类的每个项的可见性。因此,在下面的示例中,我刚刚为父级定义了一个私有变量,这样子级就无法看到它,但子级可以通过公共getter setters更新该变量。这是因为我们使用getter和setter来提供封装,因为它只与父类相关。请调查代码以了解更多信息:

class Main {

    public static class Parent {
        private int variable;

        public int getVariable() {
            return variable;
        }

        public void setVariable(int variable) {
            this.variable = variable;
        }
    }

    public static class Child extends Parent {

        private int childVadiable;

        public Child() {

        }

        public int getChildVadiable() {
            return childVadiable;
        }

        public void setChildVadiable(int childVadiable) {
            this.childVadiable = childVadiable;
        }

        public void updateParentVariable(int value) {
            this.setVariable(value);
        }

    }

    public static void main (String[] args) {

        Child child = new Child();
        child.updateParentVariable(5);
        System.out.println(child.getVariable());
        //Result it '5'
    }

}

您能展示代码吗?我认为您应该使用Java book而不是stackoverflow…子级已经从其父级继承了(公共和受保护)变量,因此您可以使用这个来访问和更改它。variable.public类HelloWorld{//参数是使用此编辑器公共静态void main(字符串[]args)下面的文本字段传递的{Parent p=new Parent();Child c=new Child();c.changeValue();//我不确定为什么这行显示12的输出应该是5 System.out.println(p.j);}}}类父级{public int j=12;}类子级扩展父级{public void changeValue(){super.j=5;System.out.println(this.j);System.out.println(super.j);}}@Raptor我可以更改child的值,这不是问题,但我想询问是否可以像我在示例代码中尝试更改的那样更改父实际值