aspose file tools*
The moose likes Associate Certification (SCJA,OCAJ 5/6) and the fly likes Polymorphism question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Associate Certification (SCJA,OCAJ 5/6)
Bookmark "Polymorphism question" Watch "Polymorphism question" New topic
Author

Polymorphism question

Chandella Montero
Ranch Hand

Joined: Feb 18, 2011
Posts: 89
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!

OCA, OCP Java 6
Mala Gupta
Author
Ranch Hand

Joined: Sep 27, 2002
Posts: 251
    
    9
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


Author of Manning's OCA Java SE 7 Programmer I Certification Guide and OCP Java SE 7 Programmer II Certification Guide
Chandella Montero
Ranch Hand

Joined: Feb 18, 2011
Posts: 89
That helps a lot, Mala. It's what I was thinking, but you made it crystal clear with an example.

Thank you!

 
 
subject: Polymorphism question