1
public class InheritanceDemo {

    public static void main(String[] args) {

        ParentClass p = new ParentClass();
        ChildClass c = new ChildClass();

        //Casting ChildClass to ParentClass
        ParentClass pc = new ChildClass();
        pc.parentClassMethod(); //Output: Parent Class Method (as expected)

        //Again Casting Parent Class to ChildClass explictly
        //Question 1 for this code
        ChildClass cp = (ChildClass) pc;
        cp.parentClassMethod(); //Output: Parent Class Method (unexpected)

        ChildClass cc1 = (ChildClass) new ParentClass();
        cc1.parentClassMethod(); //Compiles, but Run Time Error

        ChildClass cc2 = (ChildClass) p;
        cc2.parentClassMethod(); //Compiles, but Run Time Error

    }
}

class ParentClass {

    public void parentClassMethod(){
        System.out.println("Parent Class Method");
    }

}

class ChildClass extends ParentClass {

    public void ParentClassMethod(){
        System.out.println("Parent Class Method From Child Class");
    }

    public void ChildClassMethod(){
        System.out.println("Child Class Method");
    }

}

Question1:

Now, I have a method called parentClassMethod in both ParentClass and ChildClass classes(Overridden). When I cast the ParentClass to ChildClass and then call the parentClassMethod, why is it executing the ParentClass method instead of the method from ChildClass if cp is refering to ChildClass?

Question2:

(i) ChildClass cp = (ChildClass) pc;

(ii) ChildClass cc1 = (ChildClass) new ParentClass(); (iii) ChildClass cc2 = (ChildClass) p;

If (i) is working fine, why not (ii) or (iii)?

Because I am casting from ParentClass to ChildClass in both the cases?

4

2 回答 2

1

Now, I have a method called parentClassMethod in both ParentClass and ChildClass classes(Overridden).

No you don't. You have a method named parentClassMethod in ParentClass and a method named ParentClassMethod in ChildClass. Since all Java identifiers are case-sensitive, there is no association between the two. ParentClassMethod does not override parentClassMethod from ParentClass.

If (i) is working fine, why not (ii) or (iii)?

In (ii) and (iii) you are trying to cast an instance of ParentClass to an instance of ChildClass. That is not allowed, as a ChildClass is-not-a ParentClass, any more than an Object is a String.

In (i) you are trying to cast an instance of ChildClass (stored in a reference declared as ParentClass) to a ChildClass, which is allowed.

When casting, it's the runtime type that counts (in other words, what T is used in new T()).

于 2013-01-19T07:23:09.017 回答
0

当泛型不存在时,让我们回到 jdk 1.4。

  Vector test = new Vector();
   test.add("java");

现在在检索您所做的事情时:

String str = (String) test.get(0);

所以字符串最初被存储为向量内的一个对象,然后你将它向下转换为字符串,它就很好了。

但是,如果您尝试以下操作,它将无法正常工作:

String str = (Object) new Object();

所以你可以看到,在第一种情况下,它是字符串,但引用是对象 [inside vector],在这种情况下,你可以向下转换,它会起作用。

要回答您的第一个问题,java 区分大小写并且您的方法名称的大小写不匹配。

于 2013-01-19T07:48:12.507 回答