Home > Net >  Exception in thread "main" error during object casting [java.lang.ClassCastException] - Ho
Exception in thread "main" error during object casting [java.lang.ClassCastException] - Ho

Time:02-21

I am writing a program which consists of several classes (2 superclasses and a couple subclasses for each). Within my driver file, I created two arrays: the first array contains objects from two completely separate classes (unrelated to each, no parent/subclass relation), and the second array contains objects that are from one of my superclass and its subclasses.

While writing and testing out the method which finds and prints the cheapest and most expensive objects from each of the arrays, I encountered an error which is related to my casting which I had to do to make the method work. I've included shorter versions of my various classes below:

//First superclass
package Plane;
public class Plane {
    
    
     private String brand;
     private double price; 
     private int horsepower;
    
     
    public Plane() {
        brand = "test";
        price = 50000.99; 
        horsepower = 500;
    }
    
    public Plane(String planeBrand, double planePrice, int planePower) {
        this.brand = planeBrand;
        this.price = planePrice;
        this.horsepower = planePower;
    }
    
    public String getBrand() {
        return this.brand;
    }
    public void setBrand(String planeBrand) {
        this.brand = planeBrand;
    }
    
    public double getPrice() {
        return this.price;
    }
    
    public void setPrice(double planePrice) {
        this.price = planePrice;
    }
    
    public int getPower() {
        return this.horsepower;
    }
    
    public void setPower(int planePower) {
        this.horsepower = planePower;
    }
    
    public Airplane(Plane plane) {
        this.brand = plane.getBrand();
        this.price = plane.getPrice();
        this.horsepower = plane.getPower();
    }
    
    public String toString() {
        return "The airplane is manufactured by "   this.brand   " and costs $"   this.price   ". It has "   this.horsepower   " horsepower.";
    }

    public boolean equals(Plane plane) {
        if (!(plane instanceof Plane) || plane == null) {
                return false;
            } else if (this.brand != plane.getBrand() || this.price != plane.getPrice() || this.horsepower != plane.getPower()) {
                    return false;
                } else {
                    return true;
                }
            }
        }
//Second superclass
package Boat;
public class Boat {

    private double weight;
    private double price;
    
    public UAV() {
        weight = 3949.5;
        price = 64000;
    }
    
    public UAV(double boatWeight, double boatPrice) {
        weight = boatWeight;
        price = boatPrice;
    }
    
    public double getWeight() {
        return this.weight;
    }
    
    public void setWeight(double boatWeight) {
        this.weight = boatWeight;
    }
    
    public double getPrice() {
        return this.price;
    }

    public void setPrice(double boatPrice) {
        this.price = boatPrice;
    }
    
    public Boat(Boat boat) {
        this.weight = boat.getWeight();
        this.price = boat.getPrice();
    }
    
    public String toString() {
        return "This boat weighs "   this.getWeight()   "kg and costs $"   this.getPrice()   ".";
    }
    
    public boolean equals(Boat boat) {
        if (!(boat instanceof Boat) || boat == null) {
            return false;
        } else if (this.price != boat.price || this.weight != boat.weight) {
            return false;
        } else {
            return true;
        }
    }
    
}
//Driver file that produces the error
public class Main {

    public static void main(String[] args) {
        
       Object[] mixedObjects = new Object[8];
        
        mixedObjects[0] = new Plane();
        mixedObjects[1] = new Plane();
        mixedObjects[2] = new Helicopter();
        mixedObjects[3] = new Helicopter();
        mixedObjects[4] = new Drone();
        mixedObjects[5] = new Drone();
        mixedObjects[6] = new Boat();
        mixedObjects[7] = new Boat();
        
        
        Object[] planeObjects = new Object[6];
        
        airplaneObjects[0] = new Plane();
        airplaneObjects[1] = new Plane();
        airplaneObjects[2] = new Helicopter();
        airplaneObjects[3] = new Helicopter();
        airplaneObjects[4] = new Drone();
        airplaneObjects[5] = new Drone();
        
        findLeastAndMostExpensiveBoat(mixedObjects);
        findLeastAndMostExpensiveBoat(planeObjects);
        //The top line is line 91 (SEE ERROR MESSAGE)

public static void findLeastAndMostExpensiveBoat(Object[] mixedObjects) {
        if(mixedObjects.length == 1 && mixedObjects[0] instanceof Boat) {
            System.out.println(mixedObjects[0]   " is the most and least expensive.");
        }
        else if(mixedObjects.length == 0) {
            System.out.println("Empty array");
        }
        else if (mixedObjects.length == 1 && !(mixedObjects[0] instanceof Boat)){
            System.out.println("No UAV object detected.");
        }
        else {
            int max = 0;
            int min = 0;
            //Maximum
            for(int i = 0 ; i< mixedObjects.length; i  ) {
                if(mixedObjects[i] instanceof Boat) {
                    System.out.println(mixedObjects[i].getClass());
            //The following line is line 157 (SEE ERROR MESSAGE)
                    if(((Boat)mixedObjects[i]).getPrice() >        ((Boat)mixedObjects[max]).getPrice()) {
                        max = i;
                    }
                } else {
                    System.out.println("No Boat object detected.");
                }
            }
            //Mininmum
            for(int i = 0 ; i< mixedObjects.length; i  ) {
                if(mixedObjects[i] instanceof Boat) {
                    if(((Boat)mixedObjects[i]).getPrice() < ((Boat)mixedObjects[min]).getPrice()) {
                        min = i;
                    }
                } else {
                    System.out.println("No Boat object detected.");
                }
            }
        } 
    }
} 

The findLeastAndMostExpensiveBoat method basically checks any array for the most expensive and cheapest boat. If no boats are present, then it prints a message saying so. The error code I get when I run my code is:

Exception in thread "main" java.lang.ClassCastException: class Plane.Plane cannot be cast to class Boat.Boat (Plane.Plane and Boat.Boat are in unnamed module of loader 'app')
    at Main.findLeastAndMostExpensiveBoat(Main.java:157)
    at Main.main(Main.java:91)

Line 91 as per error message is: findLeastAndMostExpensiveBoat(planeObjects);

Line 157 as per error message is: if(((Boat)mixedObjects[i]).getPrice() > ((Boat)mixedObjects[max]).getPrice())

Where exactly did I go wrong with my code? Is my cast syntax wrong, or is there a deeper issue I need to resolve?

CodePudding user response:

You are checking whether an object is instance of Boat by if(mixedObjects[i] instanceof Boat) but you don't certainly know that mixedObjects[max] is type of Boat. The same is true for the min case. You may add an extra condition like mixedObjects[max] instanceof Boat too.

  • Related