Java中的实例变量
请解释以下行为。
class Base
{
public int num = 3;
public int getNum()
{
return num;
}
public void setNum(int num)
{
this.num = num;
}
}
class child
extends Base
{
public int num = 4;
public child()
{
}
public child(int i)
{
this.num = i;
}
public int getNum()
{
return num;
}
public void setNum(int num)
{
this.num = num;
}
}
public class Main
{
public static void main(String[] args)
{
Base obj2 = new child();
System.out.println(obj2.num);
System.out.println(obj2.getNum());
Base obj3 = new child(10);
System.out.println(obj3.num);
System.out.println(obj3.getNum());
}
}
输出 : 3 4 3 10
这里 obj2.num 和 obj3.num 仍然指向 Base 类实例变量中分配的值 3。它不会像 obj2.getNum() 和 obj3.getNum() 一样被覆盖吗?
提前致谢。
Please explain the following behaviour.
class Base
{
public int num = 3;
public int getNum()
{
return num;
}
public void setNum(int num)
{
this.num = num;
}
}
class child
extends Base
{
public int num = 4;
public child()
{
}
public child(int i)
{
this.num = i;
}
public int getNum()
{
return num;
}
public void setNum(int num)
{
this.num = num;
}
}
public class Main
{
public static void main(String[] args)
{
Base obj2 = new child();
System.out.println(obj2.num);
System.out.println(obj2.getNum());
Base obj3 = new child(10);
System.out.println(obj3.num);
System.out.println(obj3.getNum());
}
}
Output :
3
4
3
10
Here how obj2.num and obj3.num still point to the value 3 which is assigned in the Base class instance variable. Wont it get overidded like the obj2.getNum() and obj3.getNum().
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于对象是用超类类型声明的,因此您将获得超级成员变量值。
如果对象是用子类类型声明的,则该值将被覆盖值。
如果将
Base obj3 = new child(10);
修改为child obj3 = new child(10);
则输出将为3 4 10 10
代码>这里有很好的解释
Because the objects are declared with super class type, you get the super member variable value.
If the object was declared with sub class type, the value would be overridden value.
If the
Base obj3 = new child(10);
is modified tochild obj3 = new child(10);
the output would be3 4 10 10
This is well explained here