1
我在嘗試基於類層次結構的挑戰。我必須嘗試評估並正確構建包括基於交通工具的車輛的層次結構。下面是類選項:構建類層次結構的最佳方法是什麼?
- 自行車
- 車
- 週期
- JetPlane
- RoadVehicle
- 充燃料
- 列車
- 交通運輸
- 三輪車
就結構而言,我必須決定哪些類是抽象類,哪些類擴展哪些類和哪些類是接口。
以下是我想出迄今:
交通運輸
public abstract class Transport
{
//Super class. All vehicles are a form of transportation.
}
自行車
public abstract class Bicycle extends RoadVehicle
{
//Bicycle is a road vehicle. Does not implement Refuelable as it does not use fuel. Is abstract because Cycle is its sub-class.
}
汽車
public class Car extends RoadVehicle implements Refuelable
{
//Extends RoadVehicle which extends Transport and also implements Refuelable as it uses fuel.
}
週期
public class Cycle extends Bicycle
{
//Cycle is an act which is carried out when using a Bicycle so it extends Bicycle.
}
JetPlane
public class JetPlane extends Transport implements Refuelable
{
//JetPlane is not a road vehicle but directly extends Transport because it is used as a form of transport, also implements Refuelable.
}
RoadVehicle
public abstract class RoadVehicle extends Transport
{
//All classs that are road vehicles extends this clss. This seperates the road vehicles from the non-road vehicles.
}
充燃料
public interface Refuelable
{
//An interface that declares which tyypes of transport use fuel and which do not.
}
列車
public class Train extends Transport implements Refuelable
{
//Trains are not a road veicle but do extend Transport and are refuelable.
}
三輪車
public class Tricycle extends Transport
{
//Tricycle is a form of transport for children, it is not refuelable and does not operate on the road.
}
這是正確的,或者你可以看到任何錯誤?我這樣做是爲了測試我對繼承的知識,所以任何建議或指針都會非常感激,謝謝。
問我們的意見是違反規則的。如果您希望我們改進您有疑問的事情,我們可以幫助您。如果你把這個結構化爲一棵樹來幫助你理解它是如何工作的,它會好很多。 – Fallenreaper
似乎沒問題。請記住,繼承的最佳答案通常是「不要」:優先選擇繼承。 – markspace
從高層看起來很好,但直到您正確定義行爲(方法),沒有人能夠說明。 – developer