定义一个Shape类

来源:百度知道 编辑:UC知道 时间:2024/09/21 23:20:30
定义一个Shape类,在此类中定义一个computerArea()方法,定义它的3个子类 Circle,Retangle,Triangle并在这3个类中实现computerArea()方法,最后把3个类存到1个Shape类的数组中去,并打印数组中的内容。

public class Shape {
public void computerArea(){
System.out.println("父类方法");
}
}
public class Circle extends Shape {
public void computerArea(){
System.out.println("这是Circle类里的computerArea方法");
}
}
public class Retangle extends Shape{
public void computerArea(){
System.out.println("这是Retangle类里的computerArea方法");
}
}
import java.util.ArrayList;

public class Triangle extends Shape {
public void computerArea(){
System.out.println("这是Triangle类里的computerArea方法");
}
public static void main(String[] agrs){
Circle c=new Circle();
Retangle r=new Retangle();
Triangle t=new Triangle();
ArrayList<Shape> list=new ArrayList<Shape>();
list.add(c);
list.add(r);
list.add(t);
for(Shape p:list){
p.computerArea();
}

}
}