定义类Shape,用来表示一般二维图形。Shape具有抽象方法area()和perimeter(),分别用来计算形状的面积和周长。
试定义一些二维形状类(如矩形、三角形、圆形、椭圆形等),这些类均为Shape类的子类。
abstract class AbstractShape {
public abstract double area() ;// 求面积
public abstract double perimeter() ;// 求周长
}
class Circular extends AbstractShape {
private double radius ;
public Circular(double radius) {
this.radius = radius ;
}
public double area() {
return 3.1415926 * this.radius * this.radius ;
}
public double perimeter() {
return 2 * 3.1415926 * this.radius ;
}
}
class Rectangle extends AbstractShape {
private double length ;
private double width ;
public Rectangle(double length,double width) {
this.length = length ;
this.width = width ;
}
public double area() {
return this.length * this.width ;
}
public double perimeter() {
return 2 * (this.length + this.width) ;
}
}
class Factory {
public static AbstractShape getInstance(String className,double ... args) {
if ("Circular".equalsIgnoreCase(className)) {
return new Circular(args[0]) ;
} else if ("Rectangle".equalsIgnoreCase(className)) {
return new Rectangle(args[0],args[1]) ;
} else {
return null ;
}
}
}
public class HelloWorld {
public static void main(String args[]) {
AbstractShape asa = Factory.getInstance("Circular",1.1) ;
AbstractShape asb = Factory.getInstance("Rectangle",1.5,10.2) ;
System.out.println("圆形面积:" + asa.area() + "、圆形周长:" + asa.perimeter()) ;
System.out.println("矩形面积:" + asb.area() + "、矩形周长:" + asb.perimeter()) ;
}
}
- 注意:
AbstractShape
在每个出现位置的含义!!