java.how中的继承通过超类方法更改子类的变量值

时间:2015-03-28 18:38:03

标签: 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

    }

}

请告诉我,每当我们使用继承(或扩展)时,字段(除了私有的变量和方法)都会复制到子(或子)类,或者子类可以访问这些字段吗?

2 个答案:

答案 0 :(得分:0)

我想出了一个可以帮助你的例子。您可以在子类中覆盖您的超级方法:

超级:

public class SuperClass {

    private String s = "SuperClass";

    public String getProperty() {
        return s;
    }

    public void print() {
        System.out.println(getProperty());
    }
}

子:

 public class SubClass extends SuperClass {

    private String s = "SubClass";

    @Override
    public String getProperty() {
        return s;
    }
}

用法:

SuperClass actuallySubClass = new SubClass();
actuallySubClass.print();

输出:

SubClass

因此,您无法从超类直接访问子私有字段,但您仍然可以使用覆盖的getter访问它。如果您需要更改值,您可以以类似的方式覆盖设置器。

答案 1 :(得分:0)

在这里使用对你的问题的引用你刚刚获得了对私有变量“i”的访问,当你扩展Sup类时,你刚从sup类中获得seti()方法,它在超级中设置var“i”的值class但是如果你重写Cid类中的seti()方法,那么你将能够在子类中更改i的值:

在这种情况下,您需要使用

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