[英]How to print three different types of object of an array (in which any type of object is possible to store) and print it in separates arrays?
[英]Store different object type in one array and print each one with their methods
我正在嘗試為它的汽車和子類創建父 class。 每個都有單獨的方法並將它們存儲在一個數組中,然后如果 class 是子類,請嘗試調用它的方法。
家長 class
public class car {
public String name ;
public double price ;
public car (String name , int price) {
this.name = name ;
this.price = price;
}
public String toString() {
return "car name : "+this.name
+" Price : " +this.price ;
}
}
子 class
public class CarMotors extends car {
public float MotorsCapacity ;
public CarMotors( String name, int price , float MotorsCapacity) {
super(name, price);
this.MotorsCapacity = MotorsCapacity ;
}
public float getMotorsCapacity() {
return this.MotorsCapacity;
}
}
主 class
public class Test {
public static void main(String[] args) {
car [] cars = new car[2] ;
cars[0] = new car("M3" , 78000);
cars[1] = new CarMotors("M4" , 98000 , 3.0f);
for(int i=0 ;i<2;i++){
if(cars[i] instanceof CarMotors) {
System.out.println(cars[i].getMotorsCapacity()); // error here
}else {
System.out.println(cars[i].toString());
}
}
}
}
如您所見,我無法打印 getMotorsCapacity()。 我是 Java 的新手。我認為需要進行一次轉換,但我現在不知道如何進行。
短... class只能看到你的行為。
在您的示例中, CarMotors
是Car
,這很好。
但是行為getMotorsCapacity()
是在CarMotors
中創建的,而不是在Car
中。
發生該錯誤的原因是,在變量 Car 中可以放置CarMotors
的實例,因為CarMotors
是 Car。 因此,Car 中的任何方法也在CarMotors
中,是的,您可以調用。 看看cars[i].toString()
這里沒有問題。
你需要明確地告訴編譯器:
“——哦,對了,原來這個變量是一個 Car,但我知道里面是一個 CarMotors。我會在這里做一個轉換,編譯器好嗎?謝謝。”
System.out.println(((CarMotors) cars[i]).getMotorsCapacity());
或者,更明確地說:
CarMotors carMotors = ((CarMotors) cars[i]);
System.out.println(carMotors.getMotorsCapacity());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.