• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

creating a superclass reference and a subclass object problem

 
Ranch Hand
Posts: 634
Eclipse IDE Chrome Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.

 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Eclipse IDE Chrome Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks, Matthew
 
Rancher
Posts: 618
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic