package _02_第二章类与对象.C202_02_01_坐标类;
public class Test {
public static void main(String[] args) {
Point p1;//声明一个引用
p1 = new Point(); //实例化一个对象,并让p1引用(指向)它
Point p2 = new Point();
//p1.x=3 错误的; 私有成员不允许外部访问
//init(0,0); 成员方法只能通过对象调用
p1.init(0,0);
p2.init(3,4);
float d = p1.distance(p2);
System.out.println(d); //这么写的好处在于 如果修改函数 不会扩散 只影响局部的类
}
}
package _02_第二章类与对象.C202_02_01_坐标类;
public class Point {
private float x;//x是属性
private float y;
public void init (int x,int y){ //x是形参 函数内部有效
this.x = x; //如果写成 x = x就错了 ,需要加this 不然起不到改float x的作用
this.y = y;
}
/**
* 计算两点之间的距离
* @param p 输入的坐标值
* @return 带回p点和 x,y点 之间的值
*/
public float distance(Point p){
return (float) Math.sqrt((this.x-p.x)*(this.x-p.x)+(this.y-p.y)*(this.y-p.y));
}
}
运行:
5.0