Thursday, August 1, 2013

class and interface typecasting gotcha!!


 Suppose there are two classes First and Second

 class First{

 }

 class Second{

 }

 class First and Second has no relation(inheritance) and If we write the following statement.

 First obj =  (First)new Second(); // will give error at compile time.

 As all know it will give compile time error.

 But If First(which is class in above case) would be an interface then what would happen?

 Interface First{

 }

 class Second{

 }

 Now If we write the following statement

 First objNew =  (First)new Second(); // will not give compile time error.

 This statement does not give us the compile time error.
 Why this happens in case of interface?

 Reason - In case of Interface there may be a situation that any subclass of Second implements the First interface.Thats why in java type casting of interface is allowed(Because compile is not sure at compile time).

 If we make the class Second final then compiler is sure at compile time that there can't be any subclass of Second the it will give compile time error

 interface First{

 }

 final class Second{

 }

 First objNewer =  (First)new Second(); // will give compile time error 

No comments:

Post a Comment