tags:

views:

49

answers:

3

I have a classes as below

public class Book extends Item{ ...}
public class DVD extends Item{ ...}

Book can be of type REFRENCE or ISSUE. DVD can be of type ISSUE only.

So should I create Item as follows?

public class Item {

  public enum ItemType{REFRENCE,ISSUE};
  ItemType itemtype;

}

Or I should declare seperate enum for both book and DVD?

+2  A: 

It depends. Is a DVD ISSUE the same as a book ISSUE?

If so then put it in the parent class and throw an exception if you create a REFERENCE DVD.

If it isnt then define seperate public enums in the two subclasses.

Visage
both issue are same.Which approach will be better?And can i throw a exception in a constrructor?i guess no
akshay
Then declare the enum in the base class. Otherwise you could have an ISSUE DVD and an ISSUE book where book.getType() and dvd.getType arent comparable, being distinct types.
Visage
Oh, and yes, you can throw an exception from a contructor - probably IllegalArgumentException in this case.
Visage
so which approach is better ?
akshay
both types are comparable as types just indicates if the book/item can be taken home or just can be hsued for regrence in library
akshay
No, they wont be comparable. If you have distinct enums then DVD.Type.ISSUE == Book.Type.ISSUE wont compile, as theyre different types.
Visage
+4  A: 

How about defining two interfaces Reference and Issue and Book will implement both while DVD will implement only Issue?

Teja Kantamneni
+1  A: 

By storing something's type in an enum you are going against using the object oriented features of the language. Also, I don't feel that an "item" "has a" property of being an issue/reference. It's more of an "is a" relation, which suggests you should use inheritence/interfaces. Of course the right approach depends on what your program is meant to do. Sometimes object oriented constructs can get in your way.

Cornelius Scarabeus