• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Reference Casting

 
James Tharakan
Ranch Hand
Posts: 580
Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



SuperClass s1;
SubClass s2= new SubClass();

s1=s2;
s1.fun();
((SubClass)s1).funny(); // Line 1

s1= ((SubClass)s1); // Line 2
s1.funny(); // Compiler Error


What is the difference between the statement at Line1 and Line 2.
Why i am not able to access funny() by Line2's casting
 
Ankit Garg
Sheriff
Posts: 9519
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the type of s1 is SuperClass. So you can only call methods which are in SuperClass from s1. Compiler doesn't know that s1 actually points to a SubClass object. What it knows that s1's type is SuperClass...
 
James Tharakan
Ranch Hand
Posts: 580
Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply , but..it did not clear my doubt
why is the compiler letting me acess the funny() at Line1 and not at line2
 
Ravikanth kolli
Ranch Hand
Posts: 179
Chrome Eclipse IDE Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is because Superclass doesnot have the method funny(). During compile time only the reference is considered and it is only at runtime that the actual object is taken into consideration.

So you do get an error during compile time since the reference is of superClass and it doesnot have funny
 
Harvinder Thakur
Ranch Hand
Posts: 231
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


At line 1, by using the narrowing conversion you are telling the compiler that the method is being invoked on the narrowing cast class i.e SubClass.
Since funny() is present in SubClass hence no compile time error.

Had s1 not been poiniting to an instance of SubClass then it would have thrown ClassCastException at runtime.



At line 2, you are telling the compiler that s1 will be pointing to a SubClass instance which the compiler allows since it knows that SubClass is the child of s1 reference variable type i.e. SuperClass
It in no ways is changing the reference type of s1 which remains SuperClass.
Again, had s1 not been poiniting to an instance of SubClass then it would have thrown ClassCastException at runtime.

The line following line 2, is giving a compiler error because the compiler checks the type of the reference variable s2 which is SuperClass and it does not contain the method funny().

Hope this is clear.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic