I’m studying oracle tutorials and have a few questions regarding the chapter Using an “Interface as a Type” from here so I try to understand how to invoke the method findLargest.
I’ve tried to modify a bit source code to get the better understanding, but nothing helps 🙁
here is my code:
public class RectanglePlus implements Relatable {
public int width = 0;
public int height = 0;
public RectanglePlus() {
}
public RectanglePlus(int w, int h) {
width = w;
height = h;
}
// a method for computing the area of the rectangle
public int getArea() {
return width * height;
}
// a method required to implement the Relatable interface
public int isLargerThan(Relatable other) {
RectanglePlus otherRect = (RectanglePlus) other;
if (this.getArea() < otherRect.getArea()) {
return -1;
} else if (this.getArea() > otherRect.getArea()) {
return 1;
} else {
return 0;
}
}
// and here is the method that i cant invoke
public RectanglePlus findLargest(RectanglePlus object1,
RectanglePlus object2) {
Relatable obj1 = (Relatable) object1;
Relatable obj2 = (Relatable) object2;
if ((obj1).isLargerThan(obj2) > 0) {
return object1;
} else {
return object2;
}
}
public static void main(String[] args) {
RectanglePlus test1 = new RectanglePlus(10, 20);
RectanglePlus test2 = new RectanglePlus(20, 20);
}
}
So, how can I invoke findLarge method on order to compare test1 and test 2? (I know it doesn’t make sense to find the largest object since I know it from the method isLargerThan, but I just try to understand a principle)
Its not a static method so I cant just say “RectanglePlus.findLarger(test1, test2)”.
How I do that?
Because
findLargestis notstatic, you can use anyRectanglePlusto call the function:or