Jim Park
Jim Park

Reputation: 47

Java understanding inheritance: getter and setter from parents class

Java beginner again. I am trying to understand how inheritance works and I think I kind of got it, but my code does not work as I expected and hard to figure out the reason why.

The problem is my getter and setter methods from the parents class. It doesn't seem that my code is calling them as I expect.

Here is my parent class:

class MyPoint {
    public int x, y;

    MyPoint() {
        x = 0;
        y = 0;
    }

    MyPoint(int x, int y) {
        this.x = x;
        this.y = y;
    }

    MyPoint(MyPoint myPoint) {
        x = myPoint.x;
        y = myPoint.y;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public void setX(int x) {
        if (x > 0) {
            this.x = x;
        }
    }

    public void setY(int y) {
        if (y > 0) {
            this.y = y;
        }
    }

    public String toString() {
        return "(" + x + ", " + y + ")";
    }
}

And the child class:

class MySubLine extends MyPoint {
    int x, y, x1, y1;
    MyPoint endPoint;

    public MySubLine() {
        super();
        x1 = 0;
        y1 = 0;
    }

    public MySubLine(int x, int y, int x1, int y1) {
        super(x, y);
        this.x = x;
        this.y = y;
        this.x1 = x1;
        this.y1 = y1;
    }

    public MySubLine(MyPoint p1, MyPoint p2) {
        super(p1.x, p1.y);
        x = p1.x;
        y = p2.y;
        x1 = p2.x;
        y1 = p2.y;
    }

    public int getEndX() {
        return x1;
    }

    public int getEndY() {
        return y1;
    }

    public void setEndX(int x) {
        if (x > 0) {
            this.x1 = x;
        }
    }

    public void setEndY(int y) {
        if (y > 0) {
            this.y1 = y;
        }
    }

    public double getLength() {
        return Math.sqrt(Math.pow((x1 - x), 2) + Math.pow((y1 - y), 2));
    }

    public String toString() {
        return "(" + x + ", " + y + ") to (" + x1 + ", " + y1 + ")";
    }
}

And when I try to run a test case of

MySubLine line = new MySubLine();
line.setX(40); line.setY(50);
System.out.println(line);

in my main Java file, the result I am getting is (0, 0) to (0, 0) while the expected result is (40, 50) to (0, 0).

Why arent my setter methods triggered?

Any help will be appreciated!

Upvotes: 0

Views: 390

Answers (1)

Joakim Danielson
Joakim Danielson

Reputation: 51955

You have declared x and y again in your subclass so they overshadow the variables with the same names in the super class

line.setX(40)

This will call the method in the superclass and thus setting x in MyPoint

In subclass

public String toString() {
    return "(" + x + ", " + y + ") to (" + x1 + ", " + y1 + ")";
}

this will access x and y in MySubLine which have not been modified.

Solution: remove x and y as instance members from MySubLine

Upvotes: 3

Related Questions