简体   繁体   中英

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. Code-1 is executing successfully but code-2 is giving compilation error at line-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. If does it so, then it should also throw error for code-1 also.

You get a compilation error because this line (emp11).displayEmp2(); is an invalid Java statement. You have to give a Type (class name) inside the csating parenthesis

in addition, the downcasting has to be made in the same statement that is doing the method call. emp11 is defined of type 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 . A variable whose type is Emp1 allows you only to call methods of class 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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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