java - java中的继承.如何通过父类(super class)方法改变子类的变量值

标签 java inheritance methods

class Sup
{
    private int i; //private one,not gonna get inherited.
    void seti(int s) //this is to set i.but which i is going to set becz i is also in child class?
    {
    i=s;
    System.out.println(i+"of sup class"); //to verify which i is changed

    }

}

class Cid extends Sup //this is child class
{
    private int i; //this is 2nd i. i want to change this i but isnt changing on call to the seti method
    void changi(int h) //this one is working in changing the 2nd i.
    {
        i=h;
    }
    void showci()
    {
     System.out.println(i+"of Cid class");   
    }
}

class Test
{
    public static void main(String[] args)
    {

        Cid ob= new Cid();
        ob.seti(3); //to set i of Cid class but this sets Sup class i
        ob.showci(); //result shows nothing changed from Cid class i
        ob.changi(6); // this works as i wanted
        ob.showci(); // now i can get the i changed of Cid class

    }

}

请澄清一下,每当我们使用继承(或扩展)时,字段(除私有(private)变量和方法之外的变量和方法)是否会复制到子(或子)类,或者这些字段只能由子类访问?

最佳答案

通过此处对您问题的引用,您刚刚获得了对私有(private)变量“i”的访问权限,当您扩展 Sup 类时,您刚刚从sup 类中获得了 seti() 方法,该方法在父类(super class)中设置 var“i” 的值,但是如果您重写 Cid 类中的 seti() 方法,那么您将能够更改子类中 i 的值:

在这种情况下你需要使用

Sup s = new Cid();
s.seti(10); // this will change the value of i in subclass class 

关于java - java中的继承.如何通过父类(super class)方法改变子类的变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29321058/

相关文章:

Linux 上的 Java 无法读取进程输入流

c++ - 如何 "inherit"来自 STL 类的迭代器?

c++ - 从模板 : correct constructor 继承

java - 锁和嵌套的同步方法

java - 有理数方法 - 分子和分母

java - Maven 将项目部署为 Jar - 缺少类定义

java - 缺少 ByteBuffer 上的一些绝对方法

java - onBackPressed 添加带有抽屉导航的双击退出?

python - 无法在子初始化器的列表理解中调用父方法,但显式循环有效

java - 如何在不使用 "%"运算符的情况下计算两个数字的余数/模?