【问题标题】:inheritance in java.how to change the variable value of sub class by super class methodsjava中的继承.如何通过超类方法改变子类的变量值
【发布时间】:2015-06-01 23:36:44
【问题描述】:
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

    }

}

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

【问题讨论】:

  • 真的不清楚你在问什么,抱歉。
  • 我的意思是我可以使用属于 Sup 类的方法更改 Cid 类中存在的变量。
  • 不行,Sup 类中的代码看不到Cid 类中的字段。只有您在Cid 中编写的代码才能看到Cid 中的私有字段。
  • 但变量“ i ”与两者相同。我认为“seti”方法是继承的,它包含“i”,所以它可以改变它。
  • 这就是我问以下问题的原因

标签: java inheritance methods


【解决方案1】:

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

超级:

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

【讨论】:

    【解决方案2】:

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

    在这种情况下你需要使用

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

    【讨论】:

      猜你喜欢
      • 2016-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-25
      • 2021-05-04
      • 1970-01-01
      • 2019-05-19
      相关资源
      最近更新 更多