java.java中的继承如何通过超类方法更改子类的变量值 [英] inheritance in java.how to change the variable value of sub class by super class methods

查看:136
本文介绍了java.java中的继承如何通过超类方法更改子类的变量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

推荐答案

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

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

超级:

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

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.

这篇关于java.java中的继承如何通过超类方法更改子类的变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆