Java新构造函数无法正常工作

时间:2015-04-09 06:50:15

标签: java

我使用简单的构造函数:public Point {this.x = x; this.y = y;},x& y - 点的坐标。它正在工作。在同一个包中,我添加了新的类Segment(功能:Point left,Point right)和构造函数:public Segment(int leftX,int leftY,int rightX,int rightY) {...}(左边和右边四个坐标点)。我尝试创建这个构造函数,但它不起作用。什么必须代替{...}?

我的代码:

class Point1 {
    private final int _x, _y;

    public Point1(int x, int y) {
        _x = x;
        _y = y;
    }
}

class Segment {
    private Point1 _poLeft, _poRight;

    public Segment(int leftX, int leftY, int rightX, int rightY) {}
}

2 个答案:

答案 0 :(得分:0)

问题的形式并不完美,缺乏主要代码,所以我不得不对发布的内容做出一些假设


java.awt.Point看起来更好的选择所以我用它,明确提到包以避免混淆

  

公共课点   扩展Point2D   实现Serializable

     

表示(x,y)坐标空间中的位置的点,以整数精度指定。

class SegmentofPoints {
    java.awt.Point aPoint;
    java.awt.Point bPoint;

    public SegmentofPoints(Point aPoint, Point bPoint) {
        this.aPoint = aPoint;
        this.bPoint = bPoint;
    }
}

public class Demo {
    public static void main(String[] args) {

        java.awt.Point aPoint;
        java.awt.Point bPoint;

        aPoint = new Point(1, 0);
        bPoint = new Point(2, 1);

        SegmentofPoints segment = new SegmentofPoints(aPoint, bPoint);
        System.out.println(segment.aPoint.toString() + " & "
                + segment.bPoint.toString());
    }
}

  

输出

     

java.awt.Point [x = 1,y = 0]& java.awt.Point中[X = 2,Y = 1]

答案 1 :(得分:0)

您可以在类中使用多个构造函数,具体取决于您打算如何构建它。例如,在这里我定义了2个构造函数,一个来自坐标,另一个来自已有的Point实例:

public class Segment { 
   private Point1 left, right; 

   public Segment(int leftX, int leftY, int rightX, int rightY) {
      left = new Point1(leftX, leftY);
      right = new Point1(rightX, rightY);
   }

   public Segment(Point1 left, Point1 right) {
      this.left = left;
      this.right = right;
   }
}

在Java中,您可以从另一个构建函数中调用它。这有助于保持课堂的一致性。上面的代码是:

public class Segment { 
   private Point1 left, right; 

   public Segment(Point1 left, Point1 right) {
      this.left = left;
      this.right = right;
   }

   public Segment(int leftX, int leftY, int rightX, int rightY) {
      // call the constructor above with freshly created Points
      this(new Point1(leftX, leftY), new Point1(rightX, rightY));
   }    
}