The moose likes Associate Certification (SCJA/OCAJ) and the fly likes Polymorphism question Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Professional Certification » Associate Certification (SCJA/OCAJ)
Reply Bookmark "Polymorphism question" Watch "Polymorphism question" New topic
Author

Polymorphism question

Chandella Montero
Ranch Hand

Joined: Feb 18, 2011
Posts: 85
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
Ranch Hand

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


SCWCD, SCJP
Chandella Montero
Ranch Hand

Joined: Feb 18, 2011
Posts: 85
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
 
Threads others viewed
Local Inner Classes
Interface implementation dependency resolver
Interface
Polymorphism
doubt in abstract class and methods
IntelliJ Java IDE

cast iron skillet 49er

more from paul wheaton's glorious empire of web junk: cast iron skillet diatomaceous earth rocket mass heater sepp holzer raised garden beds raising chickens lawn care CFL flea control missoula heat permaculture