Reputation: 369
I have an java assignment. Its requirement shows that there is an super-type called Module. It has two sub-type class "Compulsory Module" and "Elective Module". The former one inherits all attributes of the super-class; the latter has one extra attribute called department name.
I consider that the Compulsory Module is the same as the Module. It is right when define one sub-class which is the same as the super-class. Every module instance must be either compulsory or elective. There are no other types of module. Should I define Module as abstract class because I don't want to confuse when deciding what class should be use in the real situation. Or someone can give me some cues.
Upvotes: 1
Views: 117
Reputation: 2112
The question you should ask is: Is an Elective Module a Compulsory Module? If this is the case, than you can let Elective Module be the superclass of Compulsory Module.
Polymorphism in Java is translated into the relation "is a"
(In your assignment it is clear that the Module class should be abstract. Because it has the same "behavior" as the Elective Module class.)
Upvotes: 0
Reputation: 4004
Looks like you have an answer in your question. Looks like you're required to have 3 classes even though CompulsoryModule has no additional attributes and only extends Module.
Module itself can be abstract or not. It depends on what you're trying to achieve. In certain cases it's impossible for you to define super class Module as a non abstract class.
For instance, if Module has a method that you don't know how to implement unless you work with CompulsoryModule or ElectiveModule, then you have to define that method as abstract and thus make the whole class abstract.
Additionally, making class abstract prevents anyone from creating an instance of that class and one will only be able to instantiate a subclass. Again, that's needed in cases when certain things are not fully defined in Module itself and require a specific subclass to make sense of superclass' code.
Upvotes: 0