Java – Using Single Class or Multiple Classes for Each Type?

design-patternsjava

I currently have a Java class called "node" which has a number of fields. Which fields in the class are used depends on a field called "type". There are close to 10 (this can grow) different types of "nodes". I was wondering if it is good to have a single class to handle all types or have different class for each type. What is the best programming practice in these cases? I would like to know (or a link to similar question/tutorials) how the performance will be affected (like memory etc.) if I use a single class?

Best Answer

This is a standard case for inheritance. You do not incur performance problems due to sub-classing. If you are performing any casting between sub types and super types several if statements will be executed at run time and are used to check for cast exceptions. In your single class model you would need to check your "type" field whenever a method or field is accessed to see if that particular "type" of node has those fields available. Memory should also not be a concern because you will be creating the same number of objects in either the single class model or the inheritance model.