继承 getter 和 toString() - java

Inheritance getter and toString() - java

我在 Java 中练习继承,但在 subclass 中卡在了 getter 方法上。 这是要点 class:

package OOP.LinePoint;

public class Point {
    private int x;
    private int y;

    public Point(int x, int y){
        this.x = x;
        this.y = y;
    }
     public String toString() {
          return "Point: (" + x + "," + y + ")";
       }
    public int getX() {
        return x;
    }
    public void setX(int x) {
        this.x = x;
    }
    public int getY() {
        return y;
    }
    public void setY(int y) {
        this.y = y;
    }

}

这里是 LineSub class:

package OOP.LinePoint;

public class LineSub extends Point{
    Point end;

    public LineSub(int beginX, int beginY, int endX, int endY){
        super(beginX, beginY);
        this.end = new Point(endX, endY);
    }
    public LineSub(Point begin, Point end){
        super(begin.getX(),begin.getY());
        this.end = end;
    }
    @Override
    public String toString() {
        return "LineSub [begin=" + "(" + super.getX() +"," + super.getY() +") " + "end=" + end + "]";
    }
    public Point getEnd() {
        return end;
    }
    public void setEnd(Point end) {
        this.end = end;
    }

    public Point getBegin(){

    }
    public void setBegin(Point begin){
        setX(begin.getX());
        setY(begin.getY());
    }

}

我的问题:

1) toString() 方法。我正在尝试打印两点(开始和结束)。如您所见,结束很简单,但开始点是继承的,我知道我应该输入什么。我获得 x 和 y 点的方式是有效的,但对我来说,这似乎是一种蹩脚的方式。当然有更好的方法,你能帮我吗?

2)点getBegin()方法。我试过:

public Point getBegin(){
  return (Point)this;
 }//Not working(getting whole Point object)

public Point getBegin(){
  return new Point(getX(), getY());
 }//Very noob way

我没有别的想法,请赐教。

恕我直言,这不是继承的好用法。您的案件不是继承的有效候选人。 class 仅当符合 is-A 关系时才适合继承。

A Line 不是 Point 而是点的集合(在你的例子中它是 being 和 end)。

所以,很适合作文(Has-A)。

一行HAS一个起点和一个终点。您正在使用继承(对于起点)和组合(对于终点)来重用代码。

坚持构图,class线有两点(起点和终点)。

要开始 Point,您必须将自己转换为 Point。您可以调用您的 super.toString 来访问父 class 的 toString

    @Override
    public String toString() {
        return "LineSub [begin=" + super.toString() + "end=" + end.toString() + "]";
    }

    public Point getBegin() {
        return (Point) this;
    }

您必须投射的事实表明您的层次结构有误。这种结构通常使用两个点来实现。

public class LineSub {

    Point begin;

    Point end;