@Java
大家好,我是Ziph!
import static java.lang.Math.PI;
/**
* @Author Ziph
* @date 2020/2/20
* @Email [email protected]
*/
public class Inherit {
public static void main(String[] args) {
Circle circle = new Circle(10);
Rect rect = new Rect(10, 29);
Square square = new Square(5);
System.out.println("圆形的面积为:" + circle.area());
System.out.println("圆形的周长为:" + circle.girth());
System.out.println("矩形的面积为:" + rect.area());
System.out.println("矩形的周长为:" + rect.girth());
System.out.println("正方形的面积为:" + square.area());
System.out.println("正方形的周长为:" + square.girth());
System.out.println("下面用print方法打印的优点是:");
System.out.println("避免代码的重复,降低耦合性!");
//避免代码的重复,降低耦合性
Inherit inherit = new Inherit();
inherit.print(new Circle(10));
inherit.print(new Rect(10,20));
inherit.print(new Square(5));
}
public void print(Shape shape) {
System.out.println(shape.area());
System.out.println(shape.girth());
}
}
class Shape {//形状
public double area() {
//面积
return 0;
}
public double girth() {
//周长
return 0;
}
}
class Circle extends Shape {//圆形
private double radius;//半径
public Circle(double radius) {
this.radius = radius;
}
public double area() {
return PI * radius * radius;
}
public double girth() {
return 2 * PI * radius;
}
}
class Rect extends Shape {//矩形
private double length;//长
private double width;//宽
public Rect(double length, double width) {
this.length = length;
this.width = width;
}
public double area() {
return length * width;
}
public double girth() {
return 2 * (length + width);
}
}
class Square extends Shape {//正方形
private double length;
public Square(double length) {
this.length = length;
}
public double area() {
return length * length;
}
public double girth() {
return 4 * length;
}
}
执行结果: