Java覆盖具有不同类型的类成员

时间:2014-09-19 04:59:07

标签: java inheritance override

我有以下枚举:

public enum CarManufacturer {
    VOLKSWAGEN, CHEVROLET, DODGE, ...
}
public enum PlaneManufacturer {
    LOCKHEED, AIRBUS, BOEING, ...
}

以及以下超类:

public class Vehicle {
    int size;
    int weight;
    ...
}

我想要做的是在车内有明确的制造商,所以每个接收车辆类的人都知道它有制造商。

例如:

public class Vehicle {
    int size;
    int weight;
    int manufacturer;

    abstract int getManufacturer () {};
}

public class Plane extends Vehicle {
    PlaneManufacturer manufacturer;
    PlaneManufacturer getManufacturer () { return this.manufacturer; }
    ...
}
public class Car extends Vehicle {
    CarManufacturer manufacturer;
    CarManufacturer getManufacturer () { return this.manufacturer; }
    ...
}

这样做的最佳方式是什么?

2 个答案:

答案 0 :(得分:3)

创建一个Manufacturer界面,让你的枚举实现该界面。

public interface Manufacturer {}

public enum CarManufacturer implements Manufacturer {
    VOLKSWAGEN, CHEVROLET, DODGE, ...
}
public enum PlaneManufacturer implements Manufacturer {
    LOCKHEED, AIRBUS, BOEING, ...
}

然后在Vehicle课程中,你可以:

public class Vehicle {
    int size;
    int weight;
    Manufacturer manufacturer;

    Manufacturer getManufacturer () {
        return manufacturer;
    };
}

答案 1 :(得分:0)

每个枚举都隐式地从Enum抽象超类扩展。因此,您可以在Car超类中将该属性引用为Enum,如:

    public class Vehicle {
        int size;
        int weight;
        Enum manufacturer;

        abstract Enum getManufacturer () {};
    }