以Shape抽象类为父类,派生出子类Cicle和Rentangle
/*定义抽象类Shape*/
abstract class Shape{
protected String name;//声明被保护的变量
/*构造方法*/
public Shape(String n){
name=n;
System.out.println("名称:"+name);
}
abstract public double getArea();
abstract public double getLength();//声明getArea()和getLength()方法
}
class Circle extends Shape{ //Cicrle子类
private final double PI = 3.14;
private double radius;
public Circle(String shapeName,double r){//构造方法
super(shapeName);
radius=r;
}
public double getArea(){
return PI*radius*radius;
}
public double getLength(){
return 2*PI*radius;
}//实现抽象类中的getArea()和getLength()方法
}
/*Rectangle子类*/
class Rectangle extends Shape{
private double width;
private double height;
public Rectangle(String shapeName,double width,double height){
super(shapeName);
this.width=width;
this.height=height;
}
public double getArea(){
return width*height;
}
public double getLength(){
return 2*(width+height);
}//实现抽象类中的getArea()和getLength()方法
}
public class abstractapplication {
public static void main(String[] args) {
Shape circle =new Circle("圆",10.2);
System.out.print("圆的面积为"+circle.getArea());
System.out.println("圆的周长为"+circle.getLength());
Shape tangle = new Rectangle("矩形",6.5,10.5);
System.out.print("矩形的面积为"+tangle.getArea());
System.out.print("矩形的周长为"+tangle.getLength());
}
}