Skip to main content

Implementing an Interface

2 replies [Last post]
Joined: 2007-12-27
Points: 0

I'm a little bit confused about the section on the RectanglePlus class which implements Relatable. I'm confused about this method:

public int isLargerThan(Relatable other) {
RectanglePlus otherRect = (RectanglePlus)other;
if (this.getArea() < otherRect.getArea())
return -1;
else if (this.getArea() > otherRect.getArea())
return 1;
return 0;

In the first line you are casting other to RectanglePlus. But since other is a Relatable type, how can you just assume it will be a RectanglePlus object? What if you have a Sphere class that also implements Relatable? This would give a runtime ClassCastException error. Wouldn't you want to prevent that from happening in code, and how would you do it? Use instanceof?

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2010-08-11
Points: 0

They are not exactly assuming that other will be a RectanglePlus object. It is the way the program was designed.
If you look at the comments in the Relatable interface, the developer says that other must be instance of the same class that is implementing the isLargerThan method.
So if the class was a TrianglePlus, the code would be:
[b]public int isLargerThan(Relatable other) {
TrianglePlus otherTri = (TrianglePlus)other;
//the rest of the code

Joined: 2010-08-10
Points: 0

Do you see that the developer tried to cast the object other to type RectanglePlus ?

please review late-binding feature.Thank !

Message was edited by: oop24h

Message was edited by: oop24h