File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Junior/Associate Certification (SCJA,OCAJ 5/6/8) 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 » Junior/Associate Certification (SCJA,OCAJ 5/6/8)
Bookmark "Polymorphism question" Watch "Polymorphism question" New topic

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);

a) shape = tri

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: 280

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.


Author of Manning's OCA Java SE 8 Programmer I Certification Guide, 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!

I agree. Here's the link:
subject: Polymorphism question
It's not a secret anymore!