public class Test3 {
public void amethod(){
Base v=new Base();
another(v);
System.out.println(v.x);
}
public void another(Base v)
{
v.x=6;
Base vh=new Base();
v=vh;
System.out.println(v.x);
} public static void main(String[] args) {
Test3 ta=new Test3();
ta.amethod();
Base b=new SubClass();
System.out.println(b.x);
System.out.println(b.method());
}
}class Base{
int x=1;
int method()
{
return x;
}
}class SubClass extends Base{
int x=2;
int method(){
return x;
}
}
public void amethod(){
Base v=new Base();
another(v);
System.out.println(v.x);
}
public void another(Base v)
{
v.x=6;
Base vh=new Base();
v=vh;
System.out.println(v.x);
} public static void main(String[] args) {
Test3 ta=new Test3();
ta.amethod();
Base b=new SubClass();
System.out.println(b.x);
System.out.println(b.method());
}
}class Base{
int x=1;
int method()
{
return x;
}
}class SubClass extends Base{
int x=2;
int method(){
return x;
}
}
another(v);
System.out.println(v.x);
此处打出的是原来对象的值6
System.out.println(b.x);b明明是一个SubClass()对象, 而b.x却指向了父类的成员,为何???高手解释一哈
System.out.println(b.x);
System.out.println(b.method());
打出的是1,2
SubClass b=new SubClass();
System.out.println(b.x);
System.out.println(b.method());
打出的是2,2
此时b是一个Base对象,所以打印的是Base类的值
SubClass b=new SubClass();
此时b才是一个SubClass对象
Base b=new SubClass();
此时b是一个Base对象,所以打印的是Base类的值
SubClass b=new SubClass();
此时b才是一个SubClass对象
------------那你解释一下为何System.out.println(b.method());返回的却是子类的成员变量x的值也就是父类对象没有调用自己的method方法而去调用子类的方法??
----这句好理解然后v=vh;将引用指向新的对象了,所以先打出一个1,
----这句话也好理解然后
another(v);
System.out.println(v.x);
此处打出的是原来对象的值6
---这个地方就有点不好理解了,既然v=vh已经将v指向了新的对象了,那么就打印出来就是新指向的对象的值,怎么在方法内就指向新对象,出了方法体就指向到以前的那个对象呢?如果说方法体内的新建的对象(即new Base())生命结束了,那怎么出了这个方法后,v又怎么能重新指向以前的那个对象呢?
这行完了后是这样:
v ----> Base(1)another(v);
这行执行完了是这样:
v ----> Base(6) v(another) ----> Base(1) 改变的引用是another中的输入参数的引用,并没有改变外面v的引用
父类对象没有调用自己的method方法而去调用子类的方法??不管是父类还是子类对象,调用的都是子类的方法,因为实例化的是子类的对象,子类对象的方法将同名的父类方法覆盖了。
想要调用父类方法,只能用如下方式实现:
Base b=new Base();
System.out.println(b.method());
对于System.out.println(b.x);这样的调用,决定x是父类还是子类值的关键,是b的引用类型
对于System.out.println(b.method()); 这样的调用,决定打印值的关键是调用的method()方法是父类的方法还是子类的方法
Base vh=new Base();
v=vh; 以后v就指向vh了,它再怎么改变已经和外面的v无关了
int x=1;
int method()
{
return x;
}
}class SubClass extends Base{
int x=2;
int method(){
return x;
}
}对于SubClass与Base来说,他们的X是不同的,即各自的数据存储地址是不一样的,所以在调用v.x的时候,实际上访问的是v的声明类型的数据地址,而不是构建的对象的地址,这样做是符全面向对象的理论的,也是合乎情理的,多态的应用是对对象的方法(接口)来说的,所以通过v.方法输出的值是实际的构建的对象值,而直接访问值时,它不符合多态的初衷设计,所以得到的值自然是声明类型对象的值,而不是实际构建对象的值.