This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes why doesnt this compile? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "why doesnt this compile? " Watch "why doesnt this compile? " New topic
Author

why doesnt this compile?

Ankur kothari
Ranch Hand

Joined: Sep 06, 2009
Posts: 531


here at compile time line 1 doesnt compile....why?
some time back we had discussed that the compiler allows this to compile because at runtime test_one can refer to one of its subclasses which implements face....
Rein de Boer
Greenhorn

Joined: Jul 12, 2009
Posts: 15
as far as the compiler is concerned, test_one does not implement face (only test40), so cannot be assigned to face.
Ankur kothari
Ranch Hand

Joined: Sep 06, 2009
Posts: 531
i think we had discussed that casting between a class and an interface which doesnt implement that interface is legal....
rohan yadav
Ranch Hand

Joined: Oct 13, 2009
Posts: 156
I think it because of downcasting, i am not sure about this, as you downcast your tester class to test40 class.
Thats why its giving comilation error if you try following, it works,



Sage of The Monstrous Toad of Mount Myoboku
Ankur kothari
Ranch Hand

Joined: Sep 06, 2009
Posts: 531
this works because both are compatible with each other...the one before did not because they werent....

Ans: we cant assign one thing to another that arent in the hierarchy.... but casting between a class and an interface that arent is legal
Minhaj Mehmood
Ranch Hand

Joined: Jan 22, 2007
Posts: 400

Ankur kothari wrote:


We have to cast explicitly.


Minhaj


SCJP6 96% | SCWCD5 81% | SCDJWS5 79%
Neha Daga
Ranch Hand

Joined: Oct 30, 2009
Posts: 504
because it is determined at runtime that test_one actually refers to tester class' object.
compiler doesn't know about it and as test 40 doesn't implements face, the code doesn't compile.

explicitly casting test_one to face will work here.


SCJP 1.6 96%
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: why doesnt this compile?
 
Similar Threads
Is this Assignment legal
from Khalid Mughal review questions
Anonymous Inner class
var-args in main() ?
The same old Interface reference type issue