3

I m new in Java and I have a simple problem:

I have the following class Point:

public class Point {

    private int yAxis;
    private int xAxis;

    public Point (int x, int y)
    {
        xAxis = x;
        yAxis = y;
    }
}

I created a new class that extends class Point. I want my new class to take as arguments two objects Point. I wrote the following code but I receive the error "Implicit super constructor MyPoint() is undefined. Must explicitly invoke another constructor". How can I fix the problem?

Thanks in advance!

public class Rectangle extends Point {

    private int length1;
    private int height1;

    public Rectangle(int x, int y, int l, int h) {
        super(x, y);
        l = length1;
        h = height1;
    }

    public Rectangle(Point topLeft, Point bottonRight) {


    }
}
jmj
  • 237,923
  • 42
  • 401
  • 438
voimak
  • 311
  • 1
  • 3
  • 7
  • And just an FYI: it doesn't make sense to assign a field value to a constructor param value. For example, you write: `l = length1`. – Tom Jan 03 '12 at 09:01
  • Also... a more clear way of asking your question would be "How do I make a subclass that depends on its superclass?" – Tom Jan 03 '12 at 09:06

2 Answers2

1

Others have mentioned that you should not use inheritance. I fully agree. But I find Effective Java to be such a good reference on matters like this, that I think it's worthy of its own answer. Please see Effective Java Item 16: Favor composition over inheritance for a more in-depth discussion.

Tom
  • 21,468
  • 6
  • 39
  • 44
0

You should not use extends Point just because the Rectangle class mentions Points. The extends keyword is used to declare an is-a relationship. Ask youself is a Rectangle a Point?

If you're trying to say "This class will be using the Point-class" you should probably just import the Point class.

(You fix the error by removing extends Point.)

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • Could I solve the problem without removing exteds Point? – voimak Jan 03 '12 at 08:29
  • Yes (but it would be silly :) Since a `Rectangle` then *is a* `Point` you need to provide the `Point`-constructor with arguments (`x` and `y`). You do this by adding for instance `super(0, 0)` in the top of the second `Rectangle` constructor. – aioobe Jan 03 '12 at 08:30
  • 1
    @voimak: you could also invoke the super constructor with the x and y properties of the `topLeft` Point: `super(topLeft.getX(), topLeft.getY())` but this is only if you really want to be able to treat a rectangle as a point. – Costi Ciudatu Jan 03 '12 at 08:38
  • 1
    what about the bottomRight Point, i have to make the same super(bottomRight.getX(), bottomRight.getY())? Thanks! – voimak Jan 03 '12 at 08:56