EvanBlack
EvanBlack

Reputation: 759

Classes in Java

I am new in Java so it will be a newbie question, here it is:

I have a class Airplane. But I must have different Airplanes (like PassengerPlane or CargoPlane) Then I have to use this planes in another class (for example Airport) as Airplane.

I mean, how can I have different attributes (cargoPlane has maximum capacity, passengerPlane has maximum passengers for example) in the same class Airplane?

Thanks in advance.

Upvotes: 1

Views: 1198

Answers (2)

Nick
Nick

Reputation: 8317

Class Airplane should only have the attributes that are shared by all airplanes. Things like fuelLevel, etc.

And as others have said, the special attributes go into the Subclasses:

class Airplane {
    int fuelLevel;
}

class CargoPlane extends Airplane {
    int maxCapacity;
}

class PassengerPlane extends Airplane {
    int maxPassengers;
}

Upvotes: 1

Bala R
Bala R

Reputation: 109027

The base Airplane class could be abstract or even an interface.

class Airplane{ 
//common attributes
}

class PassengerPlane extends Airplane{
//passenger plane specific attributes
}

class CargoPlane extends Airplane{
//cargo plane specific attributes
}

class Airport
{
List<Airplane> airplanes;
// do stuff with planes

}

Upvotes: 5

Related Questions