Java基础接⼝实现设计⼀个形状类(接⼝)Shape,⽅法:求周长和求⾯积
题⽬:
设计⼀个形状类(接⼝)Shape,⽅法:求周长和求⾯积形状类(接⼝)的⼦类(实现类);:Rect(矩形),Circle(圆形)Rect类的⼦类:Square(正⽅形)不同的⼦类会有不同的计算周长和⾯积的⽅法。
创建三个不同的形状对象,放在Shape类型的数组⾥,分别打印出每个对象的周长和⾯积。
形状接⼝
public interface Shape {java接口有没有构造方法
// 求⾯积⽅法
double getArea();
// 求周长⽅法
double getPerimeter();
}
圆形类
public class Circle implements Shape {
private final double PI =3.14;//圆周率
private double r;//半径
public double getR(){
return r;
}
public void setR(double r){
this.r = r;
}
public Circle(double r){
this.r = r;
}
@Override
public double getArea(){
// TODO Auto-generated method stub
return PI * r * r;
}
@Override
public double getPerimeter(){
// TODO Auto-generated method stub
return PI * r *2;
}
}
矩形类
public class Rect implements Shape { private double width;// 宽
private double height;// ⾼
public double getWidth(){
return width;
}
public void setWidth(double width){ this.width = width;
}
public double getHeight(){
return height;
}
public void setHeight(double height){ this.height = height;
}
// ⼀个参数构造,给⼦类正⽅形⽤
public Rect(double width){
this.width = width;
}
//两个参数的构造,⾃⼰⽤
public Rect(double width,double height){ this.height = height;
this.width = width;
}
@Override
public double getArea(){
// TODO Auto-generated method stub return width * height;
}
@Override
public double getPerimeter(){
// TODO Auto-generated method stub return2*(width + height);
}
}
正⽅形,继承矩形
public class Square extends Rect { public Square(double width){
super(width);
}
@Override
public double getArea(){
// TODO Auto-generated method stub return getWidth()*getWidth();
}
@Override
public double getPerimeter(){
// TODO Auto-generated method stub return4*getWidth();
}
}
测试类
public class Test {
public static void main(String[] args){
Shape[] shape =new Shape[3];
shape[0]=new Circle(3);
System.out.println("========圆形周长和⾯积========");
System.out.println(String.format("%.2f", shape[0].getArea()));  System.out.println(shape[0].getPerimeter());
shape[1]=new Rect(5,8);
System.out.println("========矩形周长和⾯积========");
System.out.println(shape[1].getArea());
System.out.println(shape[1].getPerimeter());
shape[2]=new Square(5);
System.out.println("========正⽅形周长和⾯积========");  System.out.println(shape[2].getArea());
System.out.println(shape[2].getPerimeter());
}
}
每天进步⼀点点!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。