依旧是我的一个小练习。
编写程序
(1)设计一个接口Geometry,包含计算面积的方法getArea();
(2)设计类Circle圆形类,包括圆的半径属性。实现Geometry接口,计算圆的面积。
(3)设计Triangle矩形类,包括width和height两个属性。实现Geometry接口,计算矩形的面积
(4)分别输出圆形、矩形的面积
先创建接口Geometry:
public interface Geometry {
void getArea();
}
创建Circle圆形类:
public class Circle implements Geometry{
private double r;
public double getR() {
return r;
}
public void setR(double r) {
this.r = r;
}
public Circle() {
}
public Circle(double r) {
this.r = r;
}
@Override
public void getArea() {
double CA = 3.14 * r * r;
System.out.println("圆的面积:" + CA);
}
}
创建Triangle矩形类:
public class Triangle implements Geometry{
private double length;
private double width;
public Triangle() {}
public Triangle(double length, double width) {
this.length = length;
this.width = width;
}
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;
}
@Override
public void getArea() {
double TA = length * width;
System.out.println("矩形的面积:" + TA);
}
}
创建测试类TestGeometry:
public class TestGeometry {
public static void main(String[] args) {
// 多态,向上转型
Geometry geometry1 = new Circle(4);
Geometry geometry2 = new Triangle(4,3);
// 可以理解为强制转型:向下转型
// Circle c = (Circle) geometry1;
// c.setR(4);
geometry1.getArea();
geometry2.getArea();
// 利用数组遍历求面积
Geometry[] geometry3 = {new Circle(4),new Triangle(4,3)};
for (int i = 0; i < geometry3.length; i++) {
geometry3[i].getArea();
}
}
}