如何处理没有任何args的构造函数? - Java

时间:2017-10-10 16:12:37

标签: java

我创建了以下程序,该程序在二维平面上创建点,并且能够计算点之间的距离:

public class Point{
  public double pt1;
  public double pt2;

  Point (double pt1, double pt2){
    if (pt1 == null && pt2 == null){this.pt1 = 0; this.pt2 = 0;}
    this.pt1 = pt1;
    this.pt2 = pt2;
  }
  public double distanceTo(Point that){
    double x = this.pt1 - that.pt1;
    double y = this.pt2 - that.pt2;
    return Math.sqrt(x * x + y * y);
  }
  public static void main(String[] args){
    Point a = new Point(3, 0); 
    Point b = new Point(0, 4); 
    System.out.println(a.distanceTo(b)); 
    System.out.println((new Point(1, 1)).distanceTo(new Point())); //Check what's wrong here! Why is this throwing an error? How to handle empty args?
  }
}

当陈述最后一个print语句时,如果有0个参数被传递,我如何修改我的Point构造函数来处理(例如" new Point()")。通过检查args的长度是否正确的方法?任何建议都会有所帮助。

2 个答案:

答案 0 :(得分:2)

如果在未提供参数时需要构造函数具有默认行为,则宁可创建单独的默认构造函数。 这样,完全参数化的构造函数就更清晰了。

class Point {
  double pt1;
  double pt2;

  Point(double pt1, double pt2){
    // always set up all parameters
    this.pt1 = pt1;
    this.pt2 = pt2;
  }

  Point(){
    // default constructor calls the parameterised constructor with default values
    this(0.0, 0.0);
  }

  // other methods
}

答案 1 :(得分:0)

如果我理解你的问题!您只需添加默认构造函数defination。

ClassName(){
//Stuff you want to process and return
  }