繁体   English   中英

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

[英]inheritance in java.how to change the variable value of sub class by super class 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

    }

}

请告诉我,每当我们使用继承(或扩展)时,字段(变量和方法(私有变量除外))是否确实会复制到子类(或子类),或者子类只能访问这些字段?

我想出了一个例子,希望可以对您有所帮助。 您可以在子类中覆盖您的super方法:

超:

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来访问它。 如果您需要更改值,可以用类似的方式覆盖设置器。

当扩展Sup类时,通过这里的“对您的问题的引用”,您只能访问私有变量“ i”,您只是从sup类中获得了seti()方法,该方法在超类中设置了var“ i”的值,但是如果您将覆盖Cid类中的seti()方法,然后您将能够更改子类中i的值:

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

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

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM