There is an example of "Implementing an Interface" in Java tutorial. I have repeated this example but it doesn't work. NetBeans shows the mistake on te left of RectanglePlus
class declaration. And mistake is:
rectangleplus.RectanglePlus is not abstract and does not override abstract method isLargerThan(rectangleplus.Relatable) in rectangleplus.Relatable
I did the same as written in tutorial. Why it shows the mistake? Here is my implementation of the project.
- The name of the project is
RectanglePlus
. - The name of the package is
rectangleplus
.
1st file in the project is Interface Relatable
:
package rectangleplus;
public interface Relatable {
int isLarger(Relatable other);
}
2nd file in the project is Main Class RectanglePlus
with helper class Point
:
package rectangleplus;
public class RectanglePlus implements Relatable {
public int width = 0;
public int height = 0;
public Point origin;
// four constructors
public RectanglePlus() {
origin = new Point(0, 0);
}
public RectanglePlus(Point p) {
origin = p;
}
public RectanglePlus(int w, int h) {
origin = new Point(0, 0);
width = w;
height = h;
}
public RectanglePlus(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}
// a method for moving the rectangle
public void move(int x, int y) {
origin.x = x;
origin.y = y;
}
// 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;
}
public static void main(String[] args) {
// TODO code application logic here
}
}
class Point {
int top;
int left;
int x;
int y;
public Point(int t, int l) {
top = t;
left = l;
}
}
Why there is nothing said about abstraction in the tutorial example? Should the tutorial example work without mitakes?
Thank you.
In the interface, you declare the method
isLarger
but in the class you declareisLargerThan
Change one to the other name and it will go fine.