【问题标题】:store different object type in one array and print each one with their methods - Java将不同的对象类型存储在一个数组中并使用它们的方法打印每个对象 - Java
【发布时间】:2022-11-29 08:18:50
【问题描述】:

我正在尝试为汽车和子类创建一个父类,每个子类都有单独的方法并将它们存储在一个数组中,然后如果该类是子类,则尝试调用它的方法

家长班

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 的新手我认为需要进行转换但现在不知道如何

【问题讨论】:

  • 您使用的是哪个版本的java?
  • 当发布有关创建错误消息的代码的问题时,将错误消息包含在问题正文中会很有帮助,最好使用复制和粘贴。但是,无论如何,您尝试过System.out.println(((CarMotors) cars[i]).getMotorsCapacity());吗?

标签: java class oop methods casting


【解决方案1】:

短...一类只能看到你的行为。

在您的示例中,CarMotorsCar,没关系。

但是行为 getMotorsCapacity() 是在 CarMotors 中创建的,而不是在 Car 中创建的。

发生该错误是因为,它可以在变量 Car 中放置一个 CarMotors 的实例。因为CarMotors 是一辆汽车。所以... Car 中的任何方法也在 CarMotors 中,是的,你调用。看看cars[i].toString()这里没问题。

你需要明确地告诉编译器: “- 哦,对了,最初这个变量是一个 Car,但是,我知道里面是一个 CarMotors。我会在这里做一个转换,好的编译器?谢谢。”

System.out.println(((CarMotors) cars[i]).getMotorsCapacity());

或者,更明确地说:

CarMotors carMotors = ((CarMotors) cars[i]); 
System.out.println(carMotors.getMotorsCapacity());

【讨论】:

    猜你喜欢
    • 2014-06-19
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多