Classes and objects – references, encapsulation and inheritance
Computer ScienceAlgorithms & Problem SolvingAges 17–18
Loading…
Sign in to playStep through small Python or Java programs that define classes, create objects and call methods, and watch a memory view: variables on the stack hold arrows (references) to objects on the heap, next to a UML class diagram. Six examples cover constructors and state, aliasing and null, objects passed to and returned from methods, encapsulation with getters and setters, inheritance with overriding and polymorphism, and static members. Experiment mode lets you create objects and copy references yourself, and a Design task asks you to build a class diagram from a written specification.
Lesson: Object-oriented programming: classes, objects, references, encapsulation, inheritance and polymorphism
What it shows
A class is a blueprint that defines attributes (data) and methods (behaviour); each object created from it is an instance with its own copy of the attributes. A variable of a class type does not contain the object but a reference to it, so assigning one variable to another creates an alias, and a reference can be null (None in Python). Encapsulation keeps attributes private and exposes them through methods that can check values. A subclass inherits the members of its superclass and may override methods; at run time the object's actual class decides which version runs, which is polymorphism.
How to use
Choose Step through code, a Language and an Example, then press Step or Run and follow the highlighted line, the arrows in the memory view and the method highlighted in the class diagram. In Experiment, create Account or SavingsAccount objects, copy references with Assign and Call methods to see aliasing, garbage and overriding. In Design task, read the specification, click members into the class boxes and press Check.
Parameters you can change
- Mode Step through code, Experiment, Design task
- Example Classes, objects and methods, References, aliasing and null, Objects as parameters and return values, Encapsulation: getters and setters, Inheritance and polymorphism, Static (class) members
- Language Python, Java
- Run speed 0.5–5 steps/s
- Design task Library book, Shapes (inheritance), Students (static members)
Questions to explore
- After c2 = c1 and c2.increment(), why does c1.count change as well?
- Why does reset(p) leave the caller's variable unchanged, while move_right(p, dx) changes the caller's object?
- In the loop over pets, why does p.describe() give a different sound for the Dog and the Cat?