Part 2 构造函数
课堂练习3:
以Point类为基础,定义一个平面中的Circle类:
1、编写一个无参的构造函数;
2、编写一个有参的构造函数;
3、在主函数中调用无参的构造函数生成圆的实例c1,调用有参的构造函数生成圆的实例c2,调用实例方法判断c1和c2是否相重叠。
public class Circles {
double x,y,r;
public Circles() {
// TODO Auto-generated constructor stub
this.x=0;
this.y=0;
this.r=1;
}
public Circles(double x, double y, double r) {
this.x = x;
this.y = y;
this.r = r;
}
public boolean overlap(Circles p) {
return Math.sqrt((p.x-this.x)*(p.x-this.x)+(p.y-this.y)*(p.y-this.y))<(p.r+this.r);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Circles p1=new Circles();
Circles P2=new Circles(1,1,0.5);
Circles P3=new Circles(2,4,1);
System.out.println(p1.overlap(P2));
System.out.println(p1.overlap(P3));
System.out.println(P2.overlap(P3));
}
}
运行结果:
本文介绍了一个基于Point类的Circle类实现,包括无参和有参构造函数的定义,以及判断两个圆是否重叠的方法。通过实例演示了如何使用这些构造函数创建圆对象,并调用方法检查它们之间的重叠情况。

805

被折叠的 条评论
为什么被折叠?



