1 .行为(创建一个点)
package exercise; //创建点类 public class Point1 { //设置属性 private double x; private double y; /* //取值的规范:getter 构成:修饰词 返回值 方法名 (参数列表){ 方法体中的代码 return 返回值 } 修饰词:public 返回值:类型与属性一致 方法名:get+属性的名字,首字母大写 参数列表:不需要 代码:没有 return 属性的名字/this.属性的名字 */ public double getX() { return x; } /* //赋值的规范:setter方法 构成:修饰词 返回值 方法名 (参数列表){ 方法体中的代码 return 返回值 } 修饰词:一定是public 返回值:不需要,这里写void 方法名:set+属性的名字,名字的首字母大写 参数列表:一般只有一个,写法:与属性同名 代码:this.属性的名字 = 参数 return:不需要 */ public void setX(double x) { this.x = x; } public double getY() { return y; } public void setY(double y) { this.y = y; } public Point1(int x, int y) { this.x = x; this.y = y; } //写方法 public double getDistance(Point1 p) {//p = p2 //因为当前方法是p1在调用,这里x,y就是p1的 //获取p2:通过参数将main中的p2传入当前方法 double temp = (x - p.x) * (x - p.x) + (y - p.y) * (y - p.y); return Math.sqrt(temp); } }
2.创建一个圆类
package work; import exercise.Point1; /** * (中)设计一个圆类,具有属性:圆心(点)、半径。添加一个方法:判断一个圆是否 * 包含一个点。 */ public class Circle { private double x; private double y; private double z; public Circle(double x, double y) { this.x = x; this.y = y; } public Circle(double z) { this.z = z; } public double getX() { return x; } public void setX(double x) { this.x = x; } public double getY() { return y; } public void setY(double y) { this.y = y; } public double getZ() { return z; } public void setZ(double z) { this.z = z; } public boolean getExist(Point1 p) {//p=p2 double temp = (x - p.getX()) * (x - p.getX()) + (y - p.getY()) * (y - p.getY()); if (temp <= z * z) { return true; } else { return false; } } }
3.调用
package work; import exercise.Point1; public class Circle1 { public static void main(String[] args) { Circle c1= new Circle(0,0); Point1 p= new Point1(2,2); c1.setZ(0.5); System.out.println(c1.getExist(p)); } }
4.结果(1)
结果(2)