定义一个父类(比如多边形),再定义一些子类(比如三角形,四边形等等)放在容器里,子类继承父类。再将子类从容器中输出。 求源程序!!!
ArrayList<Shape> list = new ArrayList<Shape>();
Triangle triangle = new Triangle();
list.add(triangle);
System.out.printl(list.get(0));
Triangle triangle = new Triangle();
list.add(triangle);
System.out.printl(list.get(0));
温馨提示:答案为网友推荐,仅供参考
第1个回答 2014-04-24
class Shape {
Shape(){
System.out.println("基础类型初始化");
}
public void area(){}
}
class TriAngle extends Shape {
int width,high;
public TriAngle(int width,int high){
this.width = width;
this.high = high;
}
public void area(){
System.out.println("三角形面积:"+ (width*high)/2);
}
}
class RectAngle extends Shape {
int width,high;
public RectAngle(int width,int high){
this.width = width;
this.high = high;
}
public void area(){
System.out.println("矩形面积:"+ (width*high)/2);
}
}
public class ShapeAreaTest {
public static void main(String args[]){
Shape baseShape;
baseShape = new TriAngle(10,10);
baseShape.area();
baseShape = new RectAngle(10,10);
baseShape.area();
}
}追问
Shape(){
System.out.println("基础类型初始化");
}
public void area(){}
}
class TriAngle extends Shape {
int width,high;
public TriAngle(int width,int high){
this.width = width;
this.high = high;
}
public void area(){
System.out.println("三角形面积:"+ (width*high)/2);
}
}
class RectAngle extends Shape {
int width,high;
public RectAngle(int width,int high){
this.width = width;
this.high = high;
}
public void area(){
System.out.println("矩形面积:"+ (width*high)/2);
}
}
public class ShapeAreaTest {
public static void main(String args[]){
Shape baseShape;
baseShape = new TriAngle(10,10);
baseShape.area();
baseShape = new RectAngle(10,10);
baseShape.area();
}
}追问
额。。。。 想问一下 容器在哪里?
追答好吧,本来想补充的,你都已经采纳了,写这么多都白搭了