-1
對於我爲學校項目編寫的這段代碼,我有很多問題。我試圖這樣做:Java層次結構和對象數組
創建和實現一個類的層次結構,其中Vehicle超類和'摩托車'和'卡車'是子類。
- 摩托車和卡車的共同點是變量車輪和重量以及方法顯示()。這些屬性不應該在課堂外訪問。 display()將打印出輪子和重量,只能通用於普通類和所有的子類。
- 摩托車級別獨有的數據應該是乘客。 Truck類獨有的數據應該是有效載荷。包含顯示此信息的方法。
- 繪製類層次結構。
- 創建一個'驅動程序'類來測試您的層次結構。允許用戶通過將引用存儲在Vehicle數組中來創建多個對象。您應該允許用戶通過輸入'm'來創建摩托車對象,然後詢問相關屬性。沿着相同的路線,使用't'來創建卡車對象。
- 輸入完所有數據後,通過調用display()方法打印出每個對象的內容。在卡車的情況下打印摩托車或載荷的人數。需要注意的是display()方法將被覆蓋了不同的子類
這裏是我的代碼原油:
import java.util.Scanner;
class Hierarchy{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
Vehicle [] garage = new Vehicle [3];
for(int i = 0; i< garage.length;i++){
System.out.println("Please enter 't' to create a truck, and 'm' for a motorcycle");
String charIn = in.nextLine();
if(charIn == "m"){
System.out.println("What is the payload of the Truck");
int payload = in.nextInt();
System.out.println("What is the weight of the Truck");
int weight = in.nextInt();
System.out.println("How many wheels does the Truck have");
int wheels = in.nextInt();
garage[i] = new Truck(payload, wheels, weight);
}else{
System.out.println("How many passengers can the Motorcycle seat");
int passengers = in.nextInt();
System.out.println("What is the weight of the Motorcycle");
int weight = in.nextInt();
System.out.println("How many wheels does the Motorcycle have");
int wheels = in.nextInt();
garage[i] = new Motorcycle(passengers, weight, wheels);
}
}
//display();
}
}
class Vehicle{
int wheels;
int weight;
public Vehicle(int wheels, int weight){
weight = this.weight;
wheels = this.wheels;
}
//private void display(int weight, int passengers, int wheels){
//}
//private void display(int weight, int payload, int wheels){
//}
}
class Truck extends Vehicle{
int payload;
public int getWheels(){
return wheels;
}
public int getWeight(){
return weight;
}
public Truck(int wheels, int payload, int weight){
super(wheels, weight);
this.payload = payload;
}
}
class Motorcycle extends Vehicle{
int passengers;
public int getWheels(){
return wheels;
}
public int getWeight(){
return weight;
}
public Motorcycle(int wheels, int passengers, int weight){
super(wheels, weight);
this.passengers = passengers;
}
}
我在儘可能多的資源試圖尋找周圍盡我所能,但我看不到將數據輸入到超類和子類中的方法,然後將信息放入一個對象(車庫數組)中。另外,任何人都可以給我一些方法來打印車庫數組的對象中的數據?當然,如果你看到任何愚蠢的錯誤,隨時告訴我。 非常感謝您的幫助!
爲了很好地打印數組,'Arrays.toString(someArray)'是你的朋友。 – azurefrog