(OJ)Java面向物件-編寫汽車類
阿新 • • 發佈:2021-01-13
技術標籤:Java
編寫汽車類
Problem Description
1.實驗目的 (1) 熟悉類的建立方法 (2) 掌握物件的宣告與建立 (3) 能利用面向物件的思想解決一般問題 2.實驗內容 編寫一個java程式,設計一個汽車類Vehicle,包含的屬性有車輪的個數wheels和車重weight。小汽車類Car是Vehicle的子類,包含的屬性有載人數loader。卡車類Truck是Car類的子類,其中包含的屬性有載重量payload。每個類都有構造方法和輸出相關資料的方法。 3.實驗要求 補充完整下面的程式碼 public class Main{ public static void main(String[] args){ Vehicle v=new Vehicle(8,10.00); smallCar c=new smallCar(6); Truck t=new Truck(10); v.disMessage(); c.disM(); t.disM2(); t.disM3(); } } // 你的程式碼
Output Description
The number of wheels in this car is 8, weight is 10.0
This car can carry 6 persons
The load of this truck is 10
The number of wheels in this truck is 8, weight is 10.0, can carry 6 persons, load of this truck is 10
解題程式碼
// Vehicle 類
class Vehicle{
// wheels 車輪個數
public int wheels;
// 重量
public double weight;
// 帶參構造方法
public Vehicle(int wheels, double weight) {
this.wheels = wheels;
this.weight = weight;
}
// 無參構造方法
public Vehicle() {
}
// 列印資訊
public void disMessage(){
System.out.println("The number of wheels in this car is " + wheels + ", weight is " + weight);
}
}
// smallCar類繼承Vehicle類
class smallCar extends Vehicle{
// loader 載人數
public int loader;
// 帶參構造 三個引數
public smallCar(int wheels, double weight, int loader) {
// 呼叫父類構造器
super(wheels, weight);
this.loader = loader;
}
// 帶參構造 一個引數
public smallCar(int loader) {
// 呼叫父類構造 根據題目輸出 wheels = 8 weight10.00
super(8, 10.00);
this.loader = loader;
}
// 無參構造
public smallCar() {
}
// 列印資訊
public void disM(){
System.out.println("This car can carry " + loader + " persons");
}
}
// Truck類繼承smallCar類
class Truck extends smallCar{
// payload 載重量
private int payload;
// 帶參構造 一個引數
public Truck(int payload) {
// 呼叫父類構造 根據題目輸出 loader = 6
super(6);
this.payload = payload;
}
// 帶參構造 四個引數
public Truck(int wheels, double weight, int loader, int payload) {
// 呼叫父類構造
super(wheels, weight, loader);
this.payload = payload;
}
// 無參構造
public Truck() {
}
// 列印資訊
public void disM2(){
System.out.println("The load of this truck is " + payload);
}
// 列印資訊
public void disM3(){
System.out.println("The number of wheels in this truck is " + wheels + ", weight is " + weight + ", can carry " + loader + " persons, load of this truck is " + payload);
}
}