• 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

Polymorphism question

 
Ranch Hand
Posts: 241
5
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm struggling to understand one of the questions from McKenzie's SCJA book (sorry Cameron, here we go again...)

Page 226, last question

Which of the following are valid lines of code, given the following:

Shape shape = new Rectangle (4,4);
IShape tri = new Triangle (5,3);
(...)
etc...

a) shape = tri
(...)
etc...

Option a is marked as correct.

A diagram is given a couple of pages before, where we can see that Shape is an abstract class and IShape is an interface that it implements.

My question: if tri is of type IShape, can it be assigned to shape, which is a variable of type Shape? Since Shape implements iShape, not the other way around, won't the compiler complain?

What if I later give tri a value that isn't a Shape, but still implements the interface IShape? Then shape = tri will be problematic, won't it?

Thank you for your help!
 
Author
Posts: 375
22
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Chandella,

As per your description, option a will not compile. Here's a simplified version of the class and interfaces that you mentioned:



A variable of super type can be used to refer to an object of its derived type. Since class Shape implements interface IShape, a variable of type IShape can be used to store an object of type Shape (or any of its derived classes). The following code will compile successfully:



Hope this helps.

cheers
Mala
 
T Vergilio
Ranch Hand
Posts: 241
5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That helps a lot, Mala. It's what I was thinking, but you made it crystal clear with an example.

Thank you!

 
reply
    Bookmark Topic Watch Topic
  • New Topic