Мой подкласс передает значения из своего суперкласса

1

Я пишу проект java, но у меня проблемы с ним. Я передаю новое значение (0, 0) и (6, 0) в моем классе Horizontal (подкласс), но когда я запускаю программу, мой вывод равен (0, 0) и (4, 4), которые являются значениями, переданными в в моем суперклассе! Я не знаю, как решить проблему! Я был бы признателен, если бы вы дали мне представление о том, где я делаю неправильно. Мне нужно следовать инструкциям!

public class Segment implements SegmentInterface {
    // two Points that hold endpoints of the segment
    private Point p1;
    private Point p2;

    // Default constructor that will set the endpoints to new
    // Points with values (0,0) and (4,4)
    public Segment() {
        //this(0, 0, 4, 4);
        this.p1 = new Point(0, 0);
        this.p2 = new Point(4, 4);
    }

    // Parameterized constructor that accepts (int x1, int y1, int x2, int y2)
    // and creates and sets the endpoints
    public Segment(int x1, int y1, int x2, int y2) {

        //this.p1 = new Point(x1, y1);
        //this.p2 = new Point(x2, y2);

        if(x1 == x2 && y1 == y2){
            throw new IllegalArgumentException("Points can't have a lenght of 0!");
        } 

        else{
            this.p1 = new Point(x1, y1);
            this.p2 = new Point(x2, y2);
    }
}

     //A parameterized constructor that accepts (Point p1, Point p2) and sets both
     //the endpoints to a deep copy of the Points that are passed in.
     //Make sure to check to see if both Points are equal.  This would be a
     //theoretical "Segment" of length 0 which is not allowed, so throw a new
     //IllegalArgumentException.
    public Segment(Point p1, Point p2) {

        this.p1 = new Point(p1.getX(), p1.getY());
        this.p2 = new Point(p2.getX(), p2.getY());

            if(p1.equals(p2)){
                throw new IllegalArgumentException("Points cannot have same values!");
            } 
}

    // Copy constructor that accepts a Segment and initializes the data (of the
    // new Segment being created) to be the same as the Segment that was
    // received.
    public Segment(Segment other) {

        this(other.p1, other.p2);

        //if(other.p1 == other.p2){
            //throw new IllegalArgumentException("Undefine!");
        //}

и вот мой подкласс:

//HorizontalSegment.java
public class HorizontalSegment extends Segment implements
        HorizontalSegmentInterface {

    protected Point p1;
    protected Point p2;

    //A default constructor that will set the endpoints to new
    //Points with values (0,0) and (6,0)
    public HorizontalSegment() {
        this.p1 = new Point(0, 0);
        this.p2 = new Point(6, 0);
    }

    /*A parameterized constructor that accepts (int x1, int y1, int x2, int y2)
     *      and creates and sets the endpoints.  But first, check to see if x1 == x2
     *      and y1== y2.  This would be a theoretical "Segment" of length 0 which
     *      is not allowed, so throw a new IllegalArgumentException like this:
     *          throw new IllegalArgumentException("whatever explanatory String you want");
     *      Also, check to see if y1 != y2.  This would be a line segment that is not
            horizontal, so throw a new IllegalArgumentException if this occurs.*/
    public HorizontalSegment(int x1, int y1, int x2, int y2) {
        super(x1, y1, x2, y2);
        if (x1 == x2 && y1 == y2) {
            throw new IllegalArgumentException("Segment of length 0 is not allowed!");
        }

        else if (y1 != y2) {
            throw new IllegalArgumentException("Line segment that is not horizontal!");
        } 

        else {
            this.p1 = new Point(x1, y1);
            this.p2 = new Point(x2, y2);
        }
    }

    /*A parameterized constructor that accepts (Point p1, Point p2) and sets both
     *      the endpoints to a deep copy of the Points that are passed in.
     *      Make sure to check to see if both Points are equal.  This would be a
     *      theoretical "Segment" of length 0 which is not allowed, so throw a new
     *      IllegalArgumentException.
     *      Also, check to see if the points form a horizontal segment.  If not, throw a
     *      new IllegalArgumentException if this occurs.*/
    public HorizontalSegment(Point p1, Point p2) {
        if (this.p1.getX() == p2.getX() && this.p1.getY() == p2.getY()) {
            throw new IllegalArgumentException(
                    "Segment of length 0 is not allowed!");

        } else if (this.p1.getY() != p2.getY()) {
            throw new IllegalArgumentException(
                    "Line segment that is not horizontal!");
        } 


        else {
            this.p1 = new Point(p1.getX(), p1.getY());
            this.p2 = new Point(p2.getX(), p2.getY());
        }
    }

    public HorizontalSegment(HorizontalSegment hs) {
        //this.p1 = hs.getP1();
        //this.p2 = hs.getP2();
        this(hs.p1, hs.p2);
    }
}
  • 1
    Используйте кнопку « Code Sample { } вместо фрагмента. Фрагменты для запуска веб-языков.
Теги:
inheritance
parameters
superclass

1 ответ

0
Лучший ответ

Поля p1 и p2 Point должны быть protected в классе Segment (не private потому что ваш подкласс не может получить к ним доступ). Таким образом, вы должны удалить их из HorizontalSegment потому что они добавляют два новых экземпляра Point с тем же именем, что и экземпляры из Segment (но они не переопределяют эти значения, они различны).

Ваш код должен работать так, как вы ожидаете, после внесения этих двух изменений.

public class HorizontalSegment extends Segment implements
        HorizontalSegmentInterface {
    // protected Point p1;
    // protected Point p2;

А также

public class Segment implements SegmentInterface {
    // two Points that hold endpoints of the segment
    protected Point p1; // <-- not private
    protected Point p2;
  • 1
    Это сработало, спасибо! :)

Ещё вопросы

Сообщество Overcoder
Наверх
Меню