创建另一个Subclass java的构造函数

时间:2014-03-06 16:08:45

标签: java inheritance constructor

如果我有班级汽车:

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 Jeepnew Sedanif( weight>3000),创建一辆吉普车mercedes=new Jeep(weight);,否则创建一个轿车mercedes=new Sedan(weight);

3 个答案:

答案 0 :(得分:8)

您似乎想要使用factory pattern。这意味着您创建了单独的类,负责构建和返回相应的Car对象。

例如:

class CarFactory {
    public Car createCar(int weight) {
         if (weight < 3000) {
              return new Sedan(weight);
         } else {
              return new Jeep(weight);
         }
    }
}

用法:

CarFactory carFactory = new CarFactory();
Car car = carFactory.createCar(yourDesiredWeight);

这不仅可以帮助您解决问题,还可以帮助您以更好的方式组织代码。即从类中操纵的类中删除了创建汽车的责任。

注意:我强烈建议您阅读single responsibility principle (SRP, for short)

注2:似乎类Car需要是抽象的,因为它是所有派生类型的通用基类,如果直接初始化(public abstract class Car {...})则没有意义。

答案 1 :(得分:2)

你不能像你想要的那样做。您正在寻找的是Abstract Factory Pattern

    public abstract class AbstractCarFactory{
      public static Car createCar(int weight){
        Car ret=null;
          if (weight>3000) {
            car=new Jeep(weight);
          } else {
            car=new Sedan(weight);
          }
        return car;
      }
    } 

添加其他选项(我不推荐并且形式很糟糕)

您可以将工厂模式合并为委托模式:

public class Car {
    private Car car;
    protected Car() {

    }
    public Car(int weight) {
        if (weight>3000) {
            car=new Jeep(weight);
        } else {
            car=new Sedan(weight);
        }
    }
    public String getType() {
        return car.getType();
    }
}

Car类将构建一辆Jeep或Sedan,并将所有呼叫委托给它。

public class Jeep extends Car {
    int weight;

    public Jeep(int weight) {
        super();
        this.weight = weight;
    }
    public String getType() {
        return "JEEP";
    }
}

同样,这是非常人为的,不应该做。

答案 2 :(得分:1)

请记住封装!

public class Car{

    private int weight ;

    public Car(){

    }

   public Car(int weight){
       this.weight = weight; 
   }

}

如果你想实例化汽车:

   Car someCar = new Car(Insert Weight Here);

您可以随时随地拨打电话。这不是通常使用继承的方式。您可能想要澄清一点。通常你会这样做:

Car somecar = new Jeep(4000);

Car somecar = new Sedan (1000);

但他们在一天结束时都是汽车