【发布时间】:2014-03-06 16:08:44
【问题描述】:
如果我有汽车类:
public class Car {
int weight;
Car(){}
public Car(int weight) {
this.weight = weight;
}
}
还有另一个继承自 Car 的 Sedan 类:
public class Sedan extends Car {
public Sedan(int weight) {
super(weight);
}
}
还有同样继承自 Car 的第三类 Jeep:
public class Jeep extends Car {
public Jeep(int weight) {
super(weight);
}
}
当我说Car mercedes = new Car(5000);时,我怎样才能做到这一点
构造函数根据给定的权重创建new Jeep 或new Sedan:if( weight>3000),创建吉普车mercedes=new Jeep(weight);,否则创建轿车mercedes=new Sedan(weight);?
【问题讨论】:
-
不在构造函数中。你需要的是一个工厂。 (调用相应构造函数的方法)
标签: java inheritance constructor