定义抽象类Shape,抽象方法为showArea(),求出面积并输出。
定义矩形类Rectangle,正方形类Square,圆类 Circle。根据各自的属性,用showArea方法求出各自的面积。
在main方法中构造3个对象,调用showArea方法。
执行代码:
package chengxu2;
abstract class Shape{
protected double area;
abstract void showArea();
}
class Rectangle extends Shape{
private double x,y;
protected Rectangle(){}
Rectangle(double x,double y){
this.x=x;
this.y=y;
}
public double getX(){
return x;
}
public double getY(){
return y;
}
public void showArea(){
area=getX()*getY();
System.out.println(area);
}
}
class Square extends Shape{
private double x;
protected Square(){}
Square(double x){
this.x=x;
}
public double getX(){
return x;
}
public void showArea(){
area=getX()*getX();
System.out.println(area);
}
}
class Circle extends Shape{
private double r;
protected Circle(){}
Circle(double r){
this.r=r;
}
public double getR(){
return r;
}
public void showArea(){
area=Math.PI*getR()*getR();
System.out.println(area);
}
}
public class test2 {
public static void main(String args[]){
Shape r=new Rectangle(4,5);
fun(r);
Shape s=new Square(4);
fun(s);
Shape c=new Circle(4);
fun(c);
}
public static void fun(Shape p){
p.showArea();
}
}
执行结果:
·先调试后运行