inheritance in java.how to change the variable value of sub class by super class methods

流过昼夜 提交于 2019-12-11 10:59:00

问题


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

    }

}

please clarify me that whenever we use inheritance(or extends) does the fields(variables and methods except private ones) do copy to the child(or sub)classes or the fields just can be accessed by the child class?


回答1:


With The Reference to your Question here you just got the access to the The private variable "i" when you extended Sup class you just got seti() method from the sup class that sets the value of var "i" in super class but if you override the seti() method in Cid class Than you will be able to change the value of i in the subclass:

In that case you need to use

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



回答2:


I have come up with an example which could hopefully help you. You could override your super method in a sub class:

super:

public class SuperClass {

    private String s = "SuperClass";

    public String getProperty() {
        return s;
    }

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

sub:

 public class SubClass extends SuperClass {

    private String s = "SubClass";

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

usage:

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

output:

SubClass

So you don't have a direct access to a sub private field as such from the superclass but you could still access it with an overriden getter. In case you need to change the value you could override the setter in the similar fashion.



来源:https://stackoverflow.com/questions/29321058/inheritance-in-java-how-to-change-the-variable-value-of-sub-class-by-super-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!