Jean-Luc Nacif Coelho
Jean-Luc Nacif Coelho

Reputation: 1022

Java override class member with different type

I have the following enums:

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

and the following superclass:

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

What i want to do is have an explicit manufacturer inside vehicle so everyone that receives a Vehicle class knows it has a manufacturer.

Ex:

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; }
    ...
}

What is the best way to do this?

Upvotes: 1

Views: 58

Answers (2)

Fernando Aires
Fernando Aires

Reputation: 531

Every enum extends from Enum abstract superclass implicitly. So, you can reference the attribute as Enum at Vehicle superclass, as in:

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

        abstract Enum getManufacturer () {};
    }

Upvotes: 0

Robby Cornelissen
Robby Cornelissen

Reputation: 97140

Create a Manufacturer interface, and have your enums implement that interface.

public interface Manufacturer {}

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

Then in your Vehicle class, you can:

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

    Manufacturer getManufacturer () {
        return manufacturer;
    };
}

Upvotes: 3

Related Questions