简体   繁体   English

Java类

[英]Classes in Java

I am new in Java so it will be a newbie question, here it is: 我是Java的新手,所以这是一个新手问题,这里是:

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. 提前致谢。

The base Airplane class could be abstract or even an interface. 基本的Airplane类可以是抽象的甚至是接口。

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

}

Class Airplane should only have the attributes that are shared by all airplanes. 飞机类应仅具有所有飞机共享的属性。 Things like fuelLevel, etc. 如FuelLevel等。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM