aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Reference Casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Reference Casting" Watch "Reference Casting" New topic
Author

Reference Casting

James Tharakan
Ranch Hand

Joined: Aug 29, 2008
Posts: 580




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


SCJP 6
Why to worry about things in which we dont have control, Why to worry about things in which we have control ! !
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9313
    
  17

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...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
James Tharakan
Ranch Hand

Joined: Aug 29, 2008
Posts: 580

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

Joined: Feb 10, 2008
Posts: 179

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


-kolli
Harvinder Thakur
Ranch Hand

Joined: Jun 10, 2008
Posts: 231


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.


thanks
Harvinder
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Reference Casting