定义一个类Shape来演示抽象类的定义和使用。
package ab;
public abstract class Shape {
double dim;
final double PI=3.14;
public Shape(double dim) {
this.dim=dim;
}
public abstract double callArea();//抽象方法,获得面积
public abstract double callPerimeter();//抽象方法,获得周长
}
建立子类Circle继承父类Shape构造方法`
package ab;
public class Circle extends Shape{
public Circle(double dim) {
super(dim);
}
public double callArea() { //实现抽象方法callArea()
return PI*dim*dim;
}
public double callPerimeter() { //实现抽象方法callPerimeter()
return 2*PI*dim;
}
}
建立子类Rectganle继承父类Shape构造方法`
package ab;
public class Rectangle extends Shape {
double width;
public Rectangle(double dim,double width){
super(dim);
this.width=width;
}
public double callArea () {
return dim*width;
}
public double callPerimeter() {
return 2*(dim+width);
}
}
测试
package ab;
public class Test {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Shape shape =new Circle(10);
//声明一个Shape对象,指向实现它的子类对象
System.out.println("圆的面积:"+shape.callArea());
//调用callArea()求圆的面积,并输出
System.out.println("圆的周长:"+shape.callPerimeter());
//调用callPerimeter()求圆的周长,并输出
Shape rect1=new Rectangle(2,5);
System.out.println("长方形的面积是:"+rect1.callArea ());
System.out.println("长方形的周长是:"+rect1.callPerimeter());
}
}
结果