wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes creating a superclass reference and a subclass object problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "creating a superclass reference and a subclass object problem" Watch "creating a superclass reference and a subclass object problem" New topic
Author

creating a superclass reference and a subclass object problem

Mohit G Gupta
Ranch Hand

Joined: May 18, 2010
Posts: 634



why is the statement at line 15 giving compile-time error and the statement at line 14 giving no error ?
i am not able to see the logic.


OCPJP 6.0 93%
OCPJWCD 5.0 98%
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4344
    
    8

Because TestOperator inherits from (or extends) Testy, we can say a TestOperator is a Testy.

On line 14 you're assigning a TestOperator object to a Test reference variable. Since all TestOperators are also Testys, this is fine.

But on line 15, you're assigning a Testy object to a TestOperator variable. But not all Testys are TestOperators - TestOperator is just one type of a Testy. So the compiler doesn't think you can do that.

Think of it in terms of classes that are intuitively obvious. E.g.

All cats are animals, so the first statement is safe. Not all animals are cats, so the second isn't.
Mohit G Gupta
Ranch Hand

Joined: May 18, 2010
Posts: 634

thanks, Matthew
Tom Reilly
Rancher

Joined: Jun 01, 2010
Posts: 618
Whereas an instance of TestOperator IS A Testy. An instance of Testy IS NOT A TestOperator. Therefore you can not assign a reference of Testy to a variable of type TestOperator
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: creating a superclass reference and a subclass object problem
 
Similar Threads
how "instanceof" operator works?
Doubt on Pno-:286(K&B) Book(instanceof)
instanceof operator???
instanceof
Collections doubt??