Inheritance allows a subclass (child class) to inherit the attributes and methods of a superclass (parent class). The subclass can then extend or override the inherited behaviour without rewriting common code.
Terminology: superclass / parent class / base class = the class being inherited from. Subclass / child class / derived class = the class that inherits.
CLASS Animal
PRIVATE name : STRING
PUBLIC PROCEDURE NEW(n : STRING)
name ← n
ENDPROCEDURE
PUBLIC FUNCTION getName() RETURNS STRING
RETURN name
ENDFUNCTION
PUBLIC PROCEDURE speak()
OUTPUT "..."
ENDPROCEDURE
ENDCLASS
CLASS Dog INHERITS Animal
PRIVATE breed : STRING
PUBLIC PROCEDURE NEW(n : STRING, b : STRING)
CALL SUPER.NEW(n) // Call parent constructor
breed ← b
ENDPROCEDURE
PUBLIC PROCEDURE speak() // Method override
OUTPUT getName() & " barks!"
ENDPROCEDURE
PUBLIC FUNCTION getBreed() RETURNS STRING
RETURN breed
ENDFUNCTION
ENDCLASS
myDog ← NEW Dog("Rex", "Labrador")
CALL myDog.speak() // Output: Rex barks!
OUTPUT myDog.getBreed() // Output: Labrador
Method overriding occurs when a subclass provides its own implementation of a method that already exists in the superclass. The overridden version replaces the parent's version when called on a subclass object.
In the example above, Dog.speak() overrides Animal.speak().
Polymorphism (meaning "many forms") allows objects of different classes to be treated as objects of a common superclass. The correct method is called at runtime based on the actual type of the object — not the variable's declared type.
This is most powerful when different subclasses override the same method — calling that method on each object produces different behaviour depending on the actual type.
// Both are Animals, but call different speak() implementations
a1 ← NEW Dog("Rex", "Lab")
a2 ← NEW Cat("Luna") // Cat also INHERITS Animal with its own speak()
CALL a1.speak() // Output: Rex barks!
CALL a2.speak() // Output: Luna meows!
A class diagram is a UML (Unified Modelling Language) diagram showing the structure of classes in an OOP system.
| Section | Contents | Notation |
|---|---|---|
| Top | Class name | ClassName |
| Middle | Attributes (with visibility and type) | - name : String (- = private, + = public) |
| Bottom | Methods (with visibility, params, return type) | + getName() : String |
| Relationship | Arrow | Meaning |
|---|---|---|
| Inheritance | Hollow arrowhead → | IS-A: Dog inherits from Animal |
| Association | Plain line | Objects use each other |
| Aggregation | Hollow diamond ◇ | HAS-A (can exist independently) |
| Composition | Filled diamond ◆ | HAS-A (cannot exist without) |
8 questions · instantly marked · AQA 7517 standard
| Term | Definition |
|---|
10 questions · 10 minutes