Java中的对象类型混淆

时间:2015-11-10 14:13:29

标签: java

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"所以任何人都可以解释这个对我来说?

5 个答案:

答案 0 :(得分: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的{​​{1}}类的执行被执行,两者都得到了“我是B”输出。

答案 1 :(得分:1)

a1=b;

bB,您可以将其分配给a1无关紧要在编译时类型所说的内容。重要的是它运行时的实际情况。由于您为a1分配了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

答案 2 :(得分: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();

答案 3 :(得分:0)

在你的代码中,a1,a2和b是你的referance变量,它指向B的实例。 首先创建A的对象

A a1 = new A();

但稍后您将其标记为“b”为

a1 = b

这就是为什么它从B类执行方法而不是从A类执行

答案 4 :(得分:0)

此图解释了将要发生的事情。上半部分显示您的代码,下半部分尝试在内存中显示它。

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

然后,你的行“a1 = b”指向b指向的对象的a1引用变量(它是相同的B()对象。

enter image description here

相关问题