提问人:Ibrahim Yahyaoui 提问时间:11/29/2022 最后编辑:Mark RotteveelIbrahim Yahyaoui 更新时间:11/29/2022 访问量:46
将不同的对象类型存储在一个数组中,并使用它们的方法打印每个对象类型
Store different object type in one array and print each one with their methods
问:
我正在尝试为汽车和子类创建一个父类。每个都有单独的方法并将它们存储在数组中,然后如果类是子类,则尝试在其上调用该方法。
父类
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 ;
}
}
子类
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;
}
}
主类
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 新手。我认为有一个演员阵容需要发生,但我现在不知道如何发生。
答:
1赞
artsmandev
11/29/2022
#1
身材矮小...一个类只能看到它的行为是什么。
在您的示例中是 ,这很好。CarMotors
Car
但是行为是在 中创建的,而不是在 .getMotorsCapacity()
CarMotors
Car
发生该错误是因为,在变量 Car 中,您可以放置一个实例,因为是 Car。所以,Car 中的任何方法也在 中,是的,你可以调用。看这里没有问题。CarMotors
CarMotors
CarMotors
cars[i].toString()
你需要明确地对编译器说:“
哦,对了,最初这个变量是一辆汽车,但我知道里面是一辆汽车。我会在这里做一个投射,好编译器吗?谢谢。
System.out.println(((CarMotors) cars[i]).getMotorsCapacity());
或者,更明确地说:
CarMotors carMotors = ((CarMotors) cars[i]);
System.out.println(carMotors.getMotorsCapacity());
评论
0赞
Mark Rotteveel
11/29/2022
使用最新版本的 Java,可以直接在 if 中完成强制转换:if (cars[i] instanceof CarMotors carMotors) { /* use carMotors instead of cars[i] */ ... }
0赞
Mark Rotteveel
11/29/2022
可以改写第一句话,因为“短......一个类只能看到它的行为是什么。对我来说没有多大意义。也许你的意思是代码只能看到变量声明类型的方法。
0赞
artsmandev
11/29/2022
是的,我现在只关注表面的方法,我不会深入研究变量、静力学@override之类的东西。
0赞
Ibrahim Yahyaoui
11/29/2022
解决方案正在工作,谢谢,我只是在我在网上阅读了一些解决方案的概念上苦苦挣扎,但我可以在不理解概念的情况下让它工作,但现在我再次感谢它。
0赞
artsmandev
11/30/2022
没关系。如果我的回答能帮助您获得更多理解,请使用它来关闭这个问题。它可能对与您情况相似的其他人有所帮助。(=
评论
System.out.println(((CarMotors) cars[i]).getMotorsCapacity());
if (cars[i] instanceof CarMotors cm) { System.out.println(cm.getMotorsCapacity()); } ...