Now the school classes have users. But so far a user does not know which school class he is in. This is because the navigation direction goes only from SchoolClass to User:

UML class and object diagrams: SchoolClass, User with direction of navigation

UML class and object diagrams: SchoolClass, User with direction of navigation

For the realization of both navigation directions an additional property schoolClass of type SchoolClass would be needed on the side of the user:

Realization of both navigation directions

Realisation of both navigation directions

So far, so good. Unfortunately, this general User would no longer be suitable for teachers or guests of the school, since they do not have a school class! In this case, this attribute would not be required (Bad programming style, because of wasted memory and less readable code).

Inheritance

A way out of this situation is the specialized user Student, which can be easily derived from the class User:

Subclass Student inherits from Superclass User

Subclass Student inherits from Superclass User

"Is an" association

Inheritance fits only if the subclass is a kind of superclass type. The Student is an User. Therefore, inheritance can also be considered as an "Is an" association.

Coding in Python

class User:                                                 # superclass "User"
    def __init__(self, surname, firstname, dateOfBirth):    # constructor 
        self._surname = surname                             # protected properties/attributes => only one "_"
        self._firstname = firstname
        self._password = firstname[0] + surname[0] + dateOfBirth  
        self._dateOfBirth = dateOfBirth
        self._username = surname 
        
    def getSurname(self):                                  
        return self._surname
    
    def getFirstname(self):
        return self._firstname

    def getPassword(self):
        return self._password

    def getDateOfBirth(self):
        return self._password

    def getUsername(self):
        return self._password


class Student(User):    # subclass "Student" inherits every property and method from superclass "User"
    def __init__(self, surname, firstname, dateOfBirth, schoolClass):
        User.__init__(self, surname, firstname, dateOfBirth)  # constructor of superclass is invoked
        self.__schoolClass = schoolClass
    def getSchoolClass(self):              
        return self.__schoolClass

Because subclasses inherit every attribute and method of superclasses ("code reuse"), only additional fields (attributes and methods) have to be defined in subclass.

Note: The access modifier private __ in the superclass must be changed to protected _ so that the subclass can also access the properties.

Last modified: Wednesday, 2 October 2019, 3:14 PM