Java 各种形状的面积与周长(继承)
面向继承与多态编程思想:代码如下:
public class GeometricManage {
public static void main(String[] args) {
Circle c01 = new Circle(10);
Rectangle r01 = new Rectangle(10,5);
System.out.printf("圆的面积为:%.2f,圆的周长为:%.2fn",c01.getArea(),c01.getPerimeter());
System.out.printf("矩形的面积为:%.2f,矩形的周长为:%.2fn",r01.getArea(),r01.getPerimeter());
}
}
class GeometricObject{
private String color;
private Boolean filled;
private Date dateCreated;
// 构造函数
protected GeometricObject(){
dateCreated = new java.util.Date();
}
protected GeometricObject(String color,boolean filled){
dateCreated = new java.util.Date();
this.color = color;
this.filled = filled;
}
// 参数返回修改方法
public String getColor(){
return color;
}
public void setColor(String color){
this.color = color;
}
public boolean isFilled(){
return filled;
}
public void setFilled(boolean filled){
this.filled = filled;
}
public java.util.Date getDateCreated(){
return getDateCreated();
}
// 方法 1.计算面积 2. 计算周长
public double getArea() {
return 0;
}
public double getPerimeter() {
return 0;
}
}
class Circle extends GeometricObject{
private double radius;
public Circle(){
}
public Circle(double radius){
this.radius = radius;
}
public Circle(double radius,String color,boolean filled){
this.radius = radius;
setColor(color);
setFilled(filled);
}
// 参数返回修改方法
public double getRadius(){
return radius;
}
public void setRadius(double radius){
this.radius = radius;
}
// 继承父类
public double getArea(){
return radius*radius* Math.PI;
}
public double getPerimeter(){
return 2*radius*Math.PI;
}
}
class Rectangle extends GeometricObject{
private double length;
private double width;
// 构造函数
public Rectangle(){
}
public Rectangle(double length,double width){
this.length = length;
this.width = width;
}
public Rectangle(double length,double width, String color,boolean filled){
this.length = length;
this.width = width;
setColor(color);
setFilled(filled);
}
// 参数返回修改方法
public double getLength(){
return length;
}
public void setLength(double length){
this.length = length;
}
public double getWidth(){
return width;
}
public void setWidth(double width){
this.width =width;
}
// 继承父类
public double getArea() {
return length*width;
}
public double getPerimeter(){
return 2*(length+width);
}
}
............



