This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
I just required a quick bit of advice on whether a simple situation best fits an abstract base class solution or an interface solution.
Say I have student, that can be either a full time or part time student, this leads me to three classes, base student, and two children. I know that i should not allow for instantiation of class 'student' by itself, so im leaning towards making it abstract, and both children classes will have almost the same methods (declared almost in exactly the same way), so again im leaning more towards an abstract base class where i can implement those methods that the children share in the base class, then let the children define and implement the 1-2 different methods that are specific to them.
However i've not sure if it is more "proper" to just make the base class an interface and implement it for both children. But this makes me think i would be repeating code? seeing as most of the methods for the two children are implemented the same, so i would have to re-declare them in both children.
It's probably a silly question thats been answered before (sorry if it has im just not the best at searching). If anyone could give me some advice on the best option i would be very thankful.
Well, in the scenario that you mention you could go with either approach. But, when you say that the both student sub-classes share same methods and implementation of the methods is also same, the interface option will definitely be a duplicacy of code. So, the abstract class suits better.
If you want even more degree of assertion then you can have an interface which will be implemented by the abstract class. Where the abstract class provides the code for methods that will be same for both sub-classes, and leaves the methods that have different implemetation for both student sub-classes as abstract.
You could have both. Define a Student interface and then implement an abstract Student class that defines all the common stuff and then extend this to create your full time and part time student classes.
Have a look at the Map interface, AbstractMap class and HashMap class for an example of this being done in the standard API.
Joined: Apr 22, 2008
Thank you for your quick replies, it makes a lot of sense the way you both described it, cleared it up for me nicely.