构造器该如何理解?
程序代码:
public class Point { double x, y; public Point() { System.out.println("这是无参构造器"); } public Point(double _x, double _y){ System.out.println("这是有参构造器"); x = _x; y = _y; } public double getDistance(Point p) { double d = Math.sqrt((x-p.x)*(x-p.x)+(y-p.y)*(y-p.y)); return d; } public static void main(String[] args) { Point p = new Point(); Point p1 = new Point(3.0, 4.0); Point origin = new Point(0, 0); System.out.println(p1.getDistance(origin)); } }
网上解释说,创建对象时系统会对这个对象的实例进行初始化,如果想改变这种初始化,就可以通过自定义构造器实现。现在有几个问题不明白:
1.
public class Point { double x, y;}本身就有x和y,public Point(double _x, double _y)这一段有有啥意义呢?
2.public double getDistance(Point p)里面的Point p是public class Point还是public Point() 还是public Point(double _x, double _y)?