【问题标题】:constructor that creates another Subclass java创建另一个子类 java 的构造函数
【发布时间】: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 Jeepnew Sedanif( weight>3000),创建吉普车mercedes=new Jeep(weight);,否则创建轿车mercedes=new Sedan(weight);

【问题讨论】:

  • 不在构造函数中。你需要的是一个工厂。 (调用相应构造函数的方法)

标签: java inheritance constructor


【解决方案1】:

您似乎想使用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);

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

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

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

【讨论】:

  • 我知道工厂模式的事情。我想知道是否可以直接在 Car 的构造函数中完成。谢谢。
  • @user120404 您无法更改实例化对象的类型,如果调用了 ctor,则表示该对象已被实例化。
【解决方案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";
    }
}

同样,这确实是人为的,不应该这样做。

【讨论】:

    【解决方案3】:

    请记住封装!

    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);
    

    但归根结底,它们都是汽车

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-02
      • 2018-10-15
      • 1970-01-01
      • 1970-01-01
      • 2015-07-02
      • 2014-03-12
      • 2012-03-24
      • 1970-01-01
      相关资源
      最近更新 更多