简体   繁体   中英

Store different object type in one array and print each one with their methods

I am trying to create a parent class for cars and subclasses from it. Each one has separate methods and store them in an array then if the class are subclass try to call the method on it.

Parent 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 ;   
    }   
}

Sub 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; 
    }
}

Main 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());
            }
        }
    }
}

As you can see, I can't print the getMotorsCapacity(). I am new to Java. I think there is a cast that need to happen, but I don't now how.

Being short... a class only can see what its yours behaviors.

In your example CarMotors is a Car , that's fine.

But the behavior getMotorsCapacity() is created in CarMotors and it wasn't in Car .

That error occurs because, it's OK in a variable Car you are able to put an instance of CarMotors because CarMotors is a Car. So, any method that is in Car is also in CarMotors , yes, you can call. Look at cars[i].toString() there's no problem here.

You need explicitly say to compiler:
"- oh, right, originally this variable is a Car, but I know that is a CarMotors inside that. I will make a cast here, OK compiler? Thanks."

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

Or, to be more clear:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM