Dean Debrio
Dean Debrio

Reputation: 57

Java ArrayList Downcasting

So I've been working in a project in which I need to have a list to be filled with its new child class objects.

I've made it with traditional method which one ArrayList will be filled with a type of child Class. But to make the code shorter and more efficient, I'm considering to downcast the ArrayList to have a single ArrayList of parent class that have both of it's child classes object inside it. Is it possible?

These are the parent class of Things

 package Model;

public class Things {
    protected String id;
    protected String name;
    protected double price;
    protected int stock;
    protected int bought;

public Things() {}

public Things(String id, String name, double price, int stock) {
    this.id = id;
    this.price = price;
    this.name = name;
    this.stock = stock;
}

public String getId() {
    return id;
}

public String getName() {
    return name;
}

public double getPrice() {
    return price;
}

public int getStock() {
    return stock;
}

public void minusStock(int bought) {
    this.stock = stock - bought;
 }
}

and these are its child class of Handphone and Vouchers

Handphone child class

package Model;

public class Handphone extends Things {
    private String color;

    public Handphone(String id, String name, double price, int stock, String color) {
        super(id, name, price, stock);
        this.color = color;
    }

    public String getColor() {
        return color;
    }
}

Voucher child class

package Model;

public class Voucher extends Things {
    private double tax;

    public Voucher(String id, String name, double price, int stock, double tax) {
        super(id, name, price, stock);
        this.tax = tax;
    }

    public double getTax() {
        return tax;
    }

    public double getsellingPrice() {
        return (price + (price*tax));
    }
}

Thus to mention the main menu interface will be on different package, I put import Model.* on it. Will it also be included inside the menu package if I put it that way?

Upvotes: 1

Views: 1633

Answers (2)

badbishop
badbishop

Reputation: 1658

If you include a field with protected getter containing the class itself into your parent class, then it will be possible to know at runtime, was it a Headphone, a Voucher or a SomethingElse.

Make sure, though, as @Maglinex suggests, that you are not looking at a design flaw.

Upvotes: 0

Magnilex
Magnilex

Reputation: 11978

You can put a Handphone and a Voucher into List<Things> (Thing would perhaps be a more appropriate name?), no need for casting:

List<Things> things = new ArrayList<>();
things.add(new Handphone("id", "name", 1, 1, "color"));

However, if you access the list and really need to know if it is a Handphone or a Voucher, you would have to downcast the object.

This type of casting could be sign of a design flaw, so carefully think your solution through.

Upvotes: 2

Related Questions