如何将对象从类转换为超类

时间:2014-09-28 14:11:36

标签: java class inheritance

我必须对防波堤进行建模,以控制某些海岸的权限。我的解决方案实现了一个类“Ship”和类“OilShip”,“FishingShip”和“CarriageShip”,我使用了继承并制作了

public class OilShip extends Ship{
 ...
} 
public class FishingShip extends Ship{
 ...
}
public class CarriageShip extends Ship{
 ...
}

在另一个班级,我有船舶船=新船(...);而且我想以某种方式将油船变成船舶,即

public Class Abcd{
  Ship ship;

  public Abcd(OilShip oship){
  ship=oship; //*************
  }
}

代码似乎有问题,请告诉我。

1 个答案:

答案 0 :(得分:0)

请务必致电超级班级'你的子类里面的构造函数'构造

这个解决方案适用于我:

public class Ship {
    private String name;
    private int weight;

    public Ship(String name, int weight) {
        this.name = name;
        this.weight = weight;
    }
}

class OilShip extends Ship {
    private int oilCapacity;

    public OilShip(int oilCapacity, String name, int weight) {
        super(name, weight);
        this.oilCapacity = oilCapacity;
    }
}

class FishingShip extends Ship {
    private int fisherMen;

    public FishingShip(int fisherMen, String name, int weight) {
        super(name, weight);
        this.fisherMen = fisherMen;
    }
}

class CarriageShip extends Ship {
    private int containers;

    public CarriageShip(int containers, String name, int weight) {
        super(name, weight);
        this.containers = containers;
    }
}

如前所述,应始终为Java类指定名称,其中第一个字符为大写,每个新单词相同 - >驼峰

你不需要不同的构造者。在这里使用继承背后的令人敬畏的事情是,无论超类中的哪个子类是什么?#34; Ship"你在" abcd"中加入你的构造函数,它将被接受:

public class Abcd {
    private Ship ship;

    public Abcd(Ship ship){
        this.ship = ship;
    }
}