2015-11-10 181 views
1
public class Test { 
    public static void main(String[] args){ 
     B b=new B(); 
     A a1=new A(); 
     A a2=b;    
     a1=b; 
     a1.printDescription(); //which prints I'm B 
     a2.printDescription(); //which also prints I'm B 
    } 
} 
class A{ 
    public void printDescription(){ 
     System.out.println("I'm A"); 
    } 
} 

class B extends A{ 
    public void printDescription(){ 
     System.out.println("I'm B"); 
    } 
} 

搜索后,我找到一个解释Confusion in Java polymorphism,其中说:“即使X为A型明确宣布,它被实例化作为B类的一个对象,所以我将运行版本在B类中定义的doIt()方法。“但是在我使用类A构造函数实例化对象之后,它仍然打印出”我是B“,那么任何人都可以为我解释这一点吗?对象类型混淆

+0

赋值'A1 = B'破阵您自己创建的新A将被覆盖。 – laune

+0

什么是您不清楚的?由于'a1 = b;'和'a2 = b','a1'和'a2'都包含'B'的实例(实际上甚至是相同的实例),并且由于多态性(或者更精确的后期绑定 - 也称为动态绑定)方法'printDescription'的代码在运行时决定,并且基于实例的实际类型(而不是引用)。 – Pshemo

回答

5
B b=new B(); // b refers to an object of class B 
    A a1=new A(); // a1 refers to an object of class A 
    A a2=b; // a2 refers to an object of class B    
    a1=b; // now a1 refers to an object of class B 

两个a1a2被分配参考b,这是指B类的对象。因此B的执行printDescription被执行,并且你得到了两个“我是B”的输出。

1
a1=b; 

bB,并且将其分配给a1。它并不重要在编译时所说的类型。重要的是它在运行时的实际状态。由于您指定了a1 a B,因此它是B

通过逐行状况:

B b=new B(); //b is a B 
A a1=new A(); //a1 is an A, b is a B 
A a2=b;  //a1 is an A, b is a B, and a2 is the same B as b 
a1=b;   //a1, a2 and b are all references to the same B value 
0

正是因为late binding。这里覆盖了方法(派生类实现了一个与base相同名称的方法)。这将导致在变量引用而不是引用类型中保存的派生类型方法将被调用,并且这将在运行时确定。

例如:

//This is an A-type reference, referencing to a A-type object 
A a = new A(); 
B b = new B(); 

//The A-type reference, is now referencing to the B-type object. 
//The old, A-type object held will be set for garbage collection. 
A a = b; 

//This will call the mostly derived type referenced method (which is B), 
//which prints "I'm B" 
a.printDescription(); 
0

在代码A1,A2和b是它们指向B. 的实例你开始创建A的一个对象作为

A a1 = new A(); 
您的全球化志愿服务青年可变

但后来你ASIGN为 “b” 为

a1 = b 

这就是为什么它是execu从B类的Ting方法不属于A类

0

该图解释了发生了什么。上半部分显示你的代码,下半部分试图在内存中显示它。

你的前三个人喜欢设置三个参考变量[b,a1和a2]。他们还设置了两个对象[new B()和new A()]。它将b指向新的B()对象,它将a1指向新的A()对象,然后它将a2指向b指向的对象。

然后,订单 “A1 = b” 的点的A1参考变量中的对象用b指向(这是相同的B()对象。

enter image description here