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.

  1. The name of the project is RectanglePlus.
  2. 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.

2

There are 2 best solutions below

0
On BEST ANSWER

In the interface, you declare the method isLarger but in the class you declare isLargerThan Change one to the other name and it will go fine.

0
On

You're not correctly implementing the isLarger() method in the Relatable interface. Rename the isLargerThan(Relatable other) method so it looks like this:

@Override
int isLarger(Relatable other) {
}

It's a good idea to use the @Override annotation, it allows you to catch errors like the one in the question.