1

Say we have a class for exams and a class for course work, and both of these require the same attributes such as the courseword/exam id, name, deadline, weight etc.

Would it be wise to create an interface so both would implement the same methods such as what i've done below? [enter image description here][ trying to look for the best OO approach, just not sure whether i'm going a little overkill.

Thank you

1 Answers1

1

I think the best approach is to create a class Class from whom ClassWork and ClassExam inherit.

The father class ClassF would declare those general attributes and the other 2 subclasses only will have to declare those specific attributes that make them unique 'cause the general ones are implied by inheritance.

I'll try to explain with an example:

       ClassF -> attributes: name, ID, weight, Date
              -> methods: getName() ....

             Exam -> attributes: marks 
                  -> methods: calculateMarks()...

             CourseWork -> attributes: typeOfCourse
                        -> methods: printInfoCourse()...

The subclasses Exam and CourseWork could implement and use for example, ID from ClassF because it's inherited from its father class.

Maybe it is a good idea to decide if you want to allow the instantiation of ClassF or not, because in that case it would be interesting to transform ClassF into an abstract class..


Just for the record in this concrete case the use of an interface to implement those classes is a wrong approach because that is not the function of an interface (https://docs.oracle.com/javase/tutorial/java/concepts/interface.html for more info)

Hope it helps!

www.admiraalit.nl
  • 5,768
  • 1
  • 17
  • 32
Jessica
  • 119
  • 5
  • Ah I like the idea of it. So say I wanted to add for example the weight of a specific course work or exam. Example: Coursework 1 = 25%, Coursework 2 = 25% and Exam = 50%. How would I implement this? what would be the approach? Also what If I want to have multiple course works or exams? wouldn't they need their own id's? –  Feb 11 '16 at 20:29
  • 1
    ClassF have that method, right? So the subclasses have it too but you want a different behavior for each subclass and in that case you have to do an @overrided of the ClassF method. Is up to you if you want to change it completely or only add some functionality. BTW, this is polymorphism! – Jessica Feb 11 '16 at 20:33
  • 1
    See http://stackoverflow.com/questions/3311788/when-to-implement-an-interface-and-when-to-extend-a-superclass – qwerty_so Feb 11 '16 at 20:40
  • I understand the concepts just can't picture the best way of doing it, the diagram that I showed does ensure the use of polymorphism –  Feb 11 '16 at 20:43
  • In your UML diagram you only have to write the method's signature in all the classes that would implemented (same name and same parameters) – Jessica Feb 11 '16 at 20:49