学习内容:以点类 Point 及平面图形类 Plane 为基础设计圆类 Circle
代码示例:
import java.util.Scanner;
class Point2{
private double x;
private double y;
public Point2(double x,double y) {
this.x=x;
this.y=y;
System.out.println("Point Constructor run");
}
public void setX(double x) {//设置x坐标
this.x=x;
}
public double getX(){//返回x坐标
return x;
}
public void setY(double y) {//设置y坐标
this.y=y;
}
public double getY(){//返回y坐标
return y;
}
public void show() {//显示点的坐标
System.out.println("Point(X="+x+",Y="+y+")");
}
}
abstract class Plane2 extends Point2{
public Plane2(double x, double y) {
super(x, y);
}
double length() {
return 0;
}
double area() {
return 0;
}
}
public class Circle extends Plane2 {
public Circle(double x, double y,double radius) {
super(x,y);
this.x=x;
this.y=y;
this.radius=radius;
System.out.println("Circle Constructorrun");
}
private double x;
private double y;
final double PI=3.14159;
private double radius;
public void setX(double x) {//设置x坐标
this.x=x;
}
public final double getX(){//返回x坐标
return x;
}
public void setY(double y) {//设置y坐标
this.y=y;
}
public final double getY(){//返回y坐标
return y;
}
public void setR(double r) {
radius=r;
}
public final double getR() {
return radius;
}
public final void show() {
System.out.println("Circle(Point("+x+","+y+"),Radius="+radius+")");
}
public final double area() {
double area=PI*radius*radius;
System.out.println("Area="+area);
return 0;
}
public final double length() {
double length=2*PI*radius;
System.out.println("Length="+length);
return 0;
}
public static void main(String[] args) {
double x=0,y=0,r=0;
Circle c1=new Circle(0, 0, 0);
Circle c2=c1;
c1.show();
System.out.println("..............................................");
c1.area();
c1.length();
System.out.println("请分别输入x,y,r:");
Scanner sc=new Scanner(System.in);
x=sc.nextDouble();
y=sc.nextDouble();
r=sc.nextDouble();
c2.setX(x);
c2.setY(y);
c2.setR(r);
c2.show();
System.out.println("..............................................");
c2.area();
c2.length();
}
}
运行截图:
明天任务:以圆类 Circle 及立体图形类 Solid 为基础设计圆柱类 Cylinder