Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

creating a superclass reference and a subclass object problem

 
Mohit G Gupta
Ranch Hand
Posts: 634
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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.

 
Matthew Brown
Bartender
Posts: 4567
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 634
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks, Matthew
 
Tom Reilly
Rancher
Posts: 618
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic