【发布时间】:2020-07-22 00:21:35
【问题描述】:
我有一个程序,其中类汽车实现了两个接口:可出租和可购买。
我的班级看起来像这样:
Class Car implements IRentable, IBuyable{
private String name;
private float rentValue;
private float sellValue;
//rentable constructor
public Car(String name, float rentValue){
...
}
//buyable constructor
public Car(String name, float buyValue){
...
}
...
}
对象的实例化看起来像这样:
IRentable c1= new Car("name",700f);
IBuyable c2= New Car ("name",35_000f);
我想知道是否有一种方法可以根据对象的静态类型调用特定的构造函数。例如,如果我有 IRentable 类型:
IRentable c1= new Car("name",700f);
调用可出租的构造函数。 如果我有 IBuyable 类型:
IBuyable c2= New Car ("name",35_000f);
调用可购买的构造函数。
【问题讨论】:
标签: java dynamic constructor interface static