Shayaan
Shayaan

Reputation: 35

How to restrict a class from taking certain types in Java?

I have a base class Product that has five subclasses (ComputerPart, Peripheral, Service, Cheese, Fruit). Each of these further have 2/3 subclasses.

Then I have a GenericOrder class that acts as a collection of an arbitrary number of objects in the Product class. GenericOrder has a subclass called ComputerOrder that will only allow ComputerPart, Peripheral and Service to be added to the order. I've spent quite some time trying to figure this out but couldn't get a reasonable answer. Please help. Here's what I have for GenericOrder:

public class GenericOrder<T>{

    private static long counter=1;
    private final long orderID = counter++;
    private List<T> orderItems;
    public GenericOrder(){
           orderItems = new ArrayList<T>();
    }
    // and so on with another constructor and add, get and set methods.
}

class ComputerOrder<T> extends GenericOrder{
//need help here
}

Any any will be greatly appreciated.....

Cheers

Upvotes: 3

Views: 782

Answers (1)

dbank
dbank

Reputation: 1213

I think you want something like this:

GenericOrder:

public class GenericOrder<T> {

    private List<T> orderItems;

    public GenericOrder() {
        orderItems = new ArrayList<T>();
    }

    public void add(T item) {
        orderItems.add(item);
    }
}

Let's define an interface that will be the only type that ComputerOrder allows:

public interface AllowableType {

}

ComputerOrder:

public class ComputerOrder extends GenericOrder<AllowableType> {

}  

Product class and family:

public class Product {

}

public class ComputerPart extends Product implements AllowableType {

}

public class Peripheral extends Product implements AllowableType {

}

public class Service extends Product implements AllowableType {

}

public class Cheese extends Product {

}

public class Fruit extends Product {

}

Now test it:

public void test() {
    ComputerOrder co = new ComputerOrder();
    co.add(new ComputerPart()); //ok
    co.add(new Peripheral());   //ok
    co.add(new Service());      //ok

    co.add(new Cheese());  //compilation error
    co.add(new Fruit());  //compilation error
}

If we want a particular type to be addable to ComputerOrder, we just need to make that type implement the AllowableType interface.

Upvotes: 3

Related Questions