【发布时间】: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