![](/img/trans.png)
[英]Storing Objects of multiple classes in an Array List, then accessing their attributes
[英]How to add objects that use attributes from multiple info classes to an array list in main program?
我有一個具有多個屬性的信息類 Vehicle ,我有一個擴展車輛類的輕便摩托車信息類。 我需要創建一個主程序,我可以將多個輕便摩托車添加到數組列表中,然后打印它們。 這是我的嘗試: info class1:
package data;
public class Vehicle {
private float price;
private String color;
private int maximumSpeed;
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color= color;
}
public int getMaximumSpeed() {
return maximumSpeed;
}
public void setMaximumSpeed(int maximumSpeed) {
this.maximumSpeed = maximumSpeed;
}
public String toString() {
return "Price: "+this.price+" Color: "+this.color+" Maximum speed: "+this.maximumSpeed;
}
}
信息類2:
package data;
public class Moped extends Vehicle{
private String Brand;
private String type;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand= brand;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String toString() {
return "Brand: "+this.brand+" Type: "+this.type;
}
}
主程序:
package app;
import java.util.ArrayList;
import java.util.Scanner;
import data.*;
public class ExtendsTest {
public static void main(String[] args) {
ArrayList<Moped> list=new ArrayList<>();
Moped mp=new Moped();
askForMopedInfo(mp);
lista.add(mp);
printMoped(list);
}
private static void printMoped(ArrayList<Mopo> list) {
for (int i=0;i<lista.size(); i++) {
System.out.println(list.get(i));
}
}
private static void askForMopedInfo(Moped mp) {
Scanner scanner = new Scanner(System.in);
System.out.print("Brand: ");
String k = scanner.nextLine();
mp.setBrad(k);
System.out.print("Type: ");
k = scanner.nextLine();
mp.setType(k);
System.out.print("Price: ");
int k1 = Integer.parseInt(scanner.nextLine());
mp.setPrice(k1);
System.out.print("Color: ");
k = scanner.nextLine();
mp.setColor(k);
System.out.print("Maximum speed: ");
k1 = Integer.parseInt(scanner.nextLine());
mp.setMaximumSpeed(k1);
}
}
當我運行程序時,我被要求:
Brand:
Type:
Price:
Color:
Maximum speed:
但程序只打印:
Brand: x Type: x
而且我仍然不確定如何將多個輕便摩托車添加到陣列列表中。 任何幫助將非常感激!
更新 Moped 類的 toString 方法,如下所示:
public String toString() {
return super.toString() +" Brand: "+this.brand+" Type: "+this.type;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.