I have four classes. Class Person, and three more, Student, Professor, Tutor, each of which extends class Person. Class Person has 2 variables studentID and staffID. However, only student can have studentID != null, and Tutors and Professors can have staffID != null. Now when creating new object Student, how can I make sure that no matter what staffID always stays null? staffID must remain in class Person, so no moving it around.
I have four classes. Class Person , and three more, Student , Professor ,
Share
Create interfaces to restrict operations:
Create your Person class:
Create your Student and Staff subclasses with the Interfaces to define the only allowed operations:
And now create your Tutors and Professors:
Objects of the Student class don’t have operations that can affect the staffId, and objects of the Staff class (including the Tutor and Professor subclasses) don’t have operations that can affect the studentId. Add other operations as necessary (common ones can go into Person directly).
As a bonus, you can use the interfaces to better define methods, like this: