简体   繁体   English

对象的多态和显式转换

[英]Polymorphism and Explicit casting of object

    //code-1
                Emp1 emp11 =  new Emp2(); 
                ((Emp2) emp11).displayEmp2();   

    //code-2
                Emp1 emp11 =  new Emp2(); 
                emp11 = (Emp2) emp11;        //line-1
                (emp11).displayEmp2();       //line-2

class Emp1  {   
    public void displayEmp1(){                
        System.out.println("displayEmp1");      
    }
}

class Emp2 extends Emp1 {
    public void displayEmp2(){
        System.out.println("displayEmp2");          
    }
}  

Why code-1 is different from code-2. 为什么代码1与代码2不同。 Code-1 is executing successfully but code-2 is giving compilation error at line-2. 代码1执行成功,但代码2在第2行给出编译错误。 Though, doing the same thing in both piece of code. 不过,在这两段代码中都做同样的事情。 I understand that it wont be able to find the method in superclass during compilation time.But my doubt is if already explicitly converting it at line-1 then why it is throwing compilation error. 我知道它在编译期间将无法在超类中找到该方法,但是我的疑问是,如果已经在第1行上对其进行了显式转换,那么它为什么会引发编译错误。 If does it so, then it should also throw error for code-1 also. 如果这样做,那么它也应该为代码1引发错误。

You get a compilation error because this line (emp11).displayEmp2(); 您收到编译错误,因为此行(emp11).displayEmp2(); is an invalid Java statement. 是无效的Java语句。 You have to give a Type (class name) inside the csating parenthesis 您必须在引用括号内输入Type(类名)

in addition, the downcasting has to be made in the same statement that is doing the method call. 另外,向下转换必须在执行方法调用的同一条语句中进行。 emp11 is defined of type Emp1 . emp11定义为Emp1类型。 it has to be explicitly casted everytime you wish to call a method from the subclass 每当您希望从子类中调用方法时,都必须对其进行显式转换

Emp1 emp11 =  new Emp2(); 
emp11 = (Emp2) emp11;
emp11.displayEmp2();  // emp11 returned to type Emp1
((Emp2)emp11).displayEmp2();  // every call to emp2 method has to be explicitly cast

Casting emp11 to Emp2 has no meaning if later you assign it back to emp11 , whose type is Emp1 . 如果稍后将其分配回类型为Emp1 emp11emp11Emp2没有任何意义。 A variable whose type is Emp1 allows you only to call methods of class Emp1 . 类型为Emp1变量仅允许您调用Emp1类的方法。

In order for the second snippet the behave as the first, you should assign the result of the casting to a variable of type Emp2 : 为了让第二个片段像第一个一样,您应该将转换结果分配给Emp2类型的变量:

Emp1 emp11 =  new Emp2(); 
Emp2 emp2 = (Emp2) emp11;
emp2.displayEmp2();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM