Meaningless Drivel is fun!
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "why doesnt this compile? " Watch "why doesnt this compile? " New topic

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

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.


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:
subject: why doesnt this compile?
jQuery in Action, 3rd edition