Object-Oriented Programming

IB Computer Science · Option: Object-Oriented Programming and Databases

Classes and objects. A class is a template describing the data (attributes) and the operations (methods) that a kind of thing has. An object is a particular instance created from that template, with its own values. A constructor is the method that runs when an object is created and puts it into a valid initial state.

Encapsulation. Attributes are declared private and access is provided through public methods. The purpose is not secrecy but control: because every change to the data must pass through a method, the class can validate input and maintain its own invariants — a bank account can refuse a withdrawal that would create a negative balance, which is impossible to guarantee if any code may write the field directly. Encapsulation also allows the internal representation to be replaced without affecting any external code, because callers depend only on the public interface.

Inheritance. A subclass acquires the attributes and methods of its superclass and adds or changes what it needs. The relationship is valid only when the statement subclass IS A superclass is true — an hourly employee is an employee. Where that is false, inheritance is the wrong tool and composition, in which one object holds another as an attribute, should be used instead. Over-using inheritance produces deep hierarchies in which a change near the root breaks distant subclasses.

Polymorphism. A subclass may override a method of its superclass with its own version. When code holds a reference typed as the superclass and calls that method, the version belonging to the object's actual class runs. The practical value is decisive: a loop that pays every employee needs no knowledge of employee types, and adding a new type later requires writing one new subclass and changing nothing in the loop. Do not confuse this with overloading, which merely means several methods share a name but take different parameters, and is resolved when the program is compiled.

Design quality. A good design has high cohesion — each class does one clearly identifiable job — and low coupling — classes interact through narrow, well-defined interfaces rather than reaching into each other's data. These two properties are what make an object-oriented program easier to test, to change and to divide among several developers; without them the paradigm delivers none of its promised benefits.

UML CLASS DIAGRAM — ENCAPSULATION, INHERITANCE AND POLYMORPHISM NhanVien - maNV : String - luongCoBan : double + tinhLuong() : double + getMaNV() : String MINUS sign = private data is hidden PLUS sign = public interface to the outside HOLLOW triangle = inheritance NhanVienGio - soGio : int + tinhLuong() : double OVERRIDE — its own formula NhanVienHoaHong - doanhSo : double + tinhLuong() : double OVERRIDE — its own formula POLYMORPHISM: call calculatePay() on a list of Employee — each object runs the version of its REAL CLASS Adding a new kind of employee does NOT require editing the code that loops over the list — that is the real value of polymorphism
The three core concepts of object-oriented programming all appear in this diagram, and the marks come from explaining what they DO, not from defining them. Encapsulation appears in the minus and plus signs. A minus sign marks a private member: the data is hidden from outside. A plus sign marks a public member: it is the interface that the rest of the program is allowed to use. The benefit is not secrecy but control: every change to the data must go through the class's methods, so the class can check validity and maintain its own invariants. It also allows the internal storage to be changed completely without affecting any code outside. Inheritance appears in the arrow with a hollow triangle head pointing up at the parent class. The two child classes receive all the attributes and methods of the Employee class without rewriting them, and then add their own parts. This relationship is only right when the statement the child class IS A parent class makes sense — an hourly employee is an employee. If that statement is not true, inheritance must not be used. Polymorphism is the purple strip at the bottom and is the concept with the greatest practical value. Both child classes override the calculatePay method with their own formula. When the program loops over a list of Employee and calls calculatePay on each element, each object runs the version belonging to its real class, even though the looping code has no idea which kind of employee it is. The value is that adding a new kind of employee only requires writing one more child class, and not a single line has to be edited in the code that loops over the list. This is the standard answer to the question of why object-oriented programming is easier to extend.

Worked example: Why encapsulation is not keeping secrets

An Account class has an attribute balance. Compare two designs: making balance public, and making balance private with the methods deposit, withdraw and getBalance. State three specific consequences of the second choice.

Then explain why the statement "encapsulation is so that other people cannot see the data" is a misunderstanding.

Solution

Consequence 1 — the class can guarantee its own invariants. If balance is public, any code anywhere in the program can assign a negative value, or a meaningless value, and the Account class has no way to prevent it. When balance is private and every change must go through withdraw, that method can check that the amount withdrawn does not exceed the balance and reject an invalid command. The invariant the balance is never negative becomes a property guaranteed by the class itself, not a convention that every programmer must remember to obey.

Consequence 2 — errors are localized to a single place. If one day an account is found with a negative balance, then with the public design the suspect is the whole program, and every line that assigns to balance must be examined. With the private design, exactly two methods can change that value, so the search for the error narrows from thousands of lines to a few dozen.

Consequence 3 — the internal representation can be replaced completely. Suppose later the system needs to store the balance as an integer number of cents to avoid floating-point error, or needs to compute the balance from a transaction history instead of storing it directly. With the private design, only the inside of the class changes; all code that calls getBalance and withdraw runs exactly as before. With the public design, every place that ever touched balance must be edited.

Why the "to keep secrets" view is wrong. The data is not hidden from anyone — the public method getBalance allows it to be read, and anyone can see the source code. What encapsulation really does is control the PATH to the data, not hide the data. In other words, it does not answer the question who is allowed to know but the question through what are changes made, and that is exactly what lets the class validate, log, and protect its own correctness.

Worked example: When inheritance is the wrong tool

A programmer writes a class StackList that inherits from a class List, the reason being that a stack needs to reuse the list's storage operations. Point out the problem and propose the correct design.

Solution

Test with the IS-A statement. Inheritance is valid only when the sentence "the child class is a parent class" is true in every context where the parent class is used. Here that sentence is FALSE: a stack is not a list. A stack has a very narrow contract — add and remove only at the top — whereas a list allows insertion and deletion at any position.

The concrete consequence of the wrong inheritance. Because the child class receives all the public methods of the parent class, users of StackList can now call the insert-in-the-middle and delete-from-the-middle methods that the List class provides. This breaks the very invariant that makes a stack: after a middle insertion, the structure no longer follows the last-in first-out principle, and any code relying on that property is silently wrong. Worse, the error does not appear in the stack class but somewhere else, far from the cause.

The second problem — coupling that is too tight. The child class depends on the implementation details of the parent class. If later the List class changes its storage or changes the behavior of a method, StackList may break with no warning sign in its own source code.

The correct design — use COMPOSITION instead of inheritance. The Stack class contains a List object as a private attribute, and publishes only three methods: push, pop and isEmpty. Internally, each of those methods calls the corresponding operation of the list. Benefits: users of Stack can only call the three valid operations, so the last-in first-out invariant is guaranteed; and the internal storage can be replaced completely — switching from a list to an array, say — without anyone outside being affected.

The principle to take away for answering every question of this kind. Use inheritance when the IS-A statement is true and when the child class can substitute for the parent class everywhere without breaking anything. Use composition when the relationship is really HAS-A or when you only want to reuse the implementation. Code reuse, in itself, is never a sufficient reason to inherit.

Common mistake

Trap 1 — explaining encapsulation as "hiding data from others". The data can still be read through public methods. What encapsulation does is CONTROL the path to the data, which lets the class check validity and change the internal representation.
Trap 2 — using inheritance only to reuse code. Inheritance is valid only when the IS-A statement is true; otherwise the child class also inherits methods that break its invariant. When you only want to reuse implementation, use COMPOSITION.
Trap 3 — confusing polymorphism with overloading. Polymorphism is overriding, resolved at RUN time by the object's real class, and its value is allowing new types to be added without editing old code. Overloading is merely several methods with the same name but different parameters, resolved at COMPILE time.

Key takeaway

Lesson 1 wrap-up. Four things to take into the exam room. One, encapsulation is for control, not for hiding, with three concrete consequences: guaranteeing invariants, narrowing the search for errors, and allowing the internal representation to change. Two, the IS-A statement is the only criterion for using inheritance; for code reuse use composition. Three, the value of polymorphism is that adding a new type only requires writing one more child class without editing old code — stating this sentence correctly earns the full marks. Four, high cohesion and low coupling are the two criteria for evaluating every object-oriented design.

← Autonomous Agents, Multi-Agent Systems and the Ethics of Autonomy · All IB Computer Science lessons · Practice IB Computer Science questions (free, instant scoring) · Relational Databases, Normalisation and Transactions →