OOP Workbench

Object-oriented programming: blueprints and the things built from them

Classes, objects, attributes, methods, constructors, encapsulation, inheritance and polymorphism, as OCR A Level H446 (topics 1.2.4 and 2.2.1) examines them. Build objects from a bank account class hierarchy, call their methods and watch what runs.

Class

A blueprint or template. It defines the attributes (data) and methods (procedures and functions) that every object of that type will have. No data is stored until an object is made.

Object

An instance of a class, created by new (instantiation). Each object has its own copy of the attributes, so two accounts can hold different balances while sharing the same methods.

Encapsulation

Attributes are made private so they can only be read or changed through the class's public methods (getters and setters), which can validate the change.

Inheritance

A subclass inherits the attributes and methods of its parent (superclass) and adds or changes some. super.new() runs the parent's constructor.

Polymorphism

Objects of different classes respond to the same method call in their own way, because a subclass can override a method. Code can treat them all as the parent type.

The class: a blueprint

Lit lines are the method that just ran

      

Reading a class definition

  1. class Account names the blueprint. Nothing exists in memory yet.
  2. private attributes hold the object's data and can only be used inside the class.
  3. public methods are the interface: the things other code is allowed to call.
  4. new is the constructor: it runs once, when an object is instantiated, and sets up the attributes.
  5. A function returns a value; a procedure does not. Getters are functions; setters and actions are usually procedures.

The objects: instances of the class

own attributeinheritedoverridden method

Make another object

Exam tips and common mistakes