IB Computer Science SL - Option D: Object-Oriented Programming Exhaustive Revision Notes
D.1 — Objects as a Programming Concept
D.1.1 — Definition of an Object - An object is considered an abstract entity composed of two primary components: - Data: These are the attributes or variables that describe the state of the object. - Actions: These are the methods or behaviours that describe what the object can do. - Purpose: Objects are used to model real-world entities within a computer program. - Examples provided in transcript: A person, an employee, a sale, a car, a date, or a music track.
D.1.2 — Class vs. Object and Instantiation - Class: Acts as a template or blueprint. It defines what attributes and methods objects of that specific type will possess. Crucially, no memory is allocated at the class level. - Instantiation: The process of creating an actual object from a class. This action triggers the allocation of memory for that specific object. - Independence: A single class can produce many independent objects, each maintaining its own unique data. - The
newKeyword: This keyword is responsible for triggering the constructor and allocating the object in memory. - Coding Example:Employee emp1 = new Employee("Walter", 356, 1000000);where: - Name: "Walter" - ID: - Salary:D.1.3 & D.1.4 — Unified Modeling Language (UML) Diagrams - Construction Sections: A UML box contains three distinct sections: Class Name, Attributes, and Methods. - Access Modifiers: -
-representsprivate. -+representspublic. -#representsprotected. - Formatting Syntax: - Attributes:- name : String(Modifier Name : Type). - Methods:+ getName() : Stringor+ setSalary(s : double) : void. - Relationships: - Inheritance ("is a"): Represented by an arrow pointing from the child class toward the parent class. - Aggregation ("has a"): Indicated by a filled diamond on the side of the class that "has many"; an arrow points toward the class being contained. - Dependency ("uses"): A plain arrow signifying that one class utilizes objects of another but does not own them. - Note on IB standards: Accessor or mutator methods do not strictly need to be included in UML diagrams for the IB assessment; their absence is not penalized.D.1.5 — Decomposition into Related Objects - Complex problems should be broken down into to related objects. - Each object must have a clearly defined role, referred to as "single responsibility." - Restaurant System Example: A system could be decomposed into
Payment,FoodItem,DrinkItem, andItemclasses. - Benefits: Reduces system complexity and improves the ease of building and maintaining the program.D.1.6 — Relationships Between Objects - "is a" (Inheritance): e.g., a Salesman is an Employee (Salesman is the child, Employee is the parent). - "has a" (Aggregation): e.g., a Salesman has many Sales (it contains instances of another class). In aggregation, if the container object is destroyed, the contained objects can still exist independently. - "uses" (Dependency): e.g., a Payment uses an Item (it references the class but does not own it).
D.1.7 — Reducing Dependencies - High dependency between objects makes a program harder to maintain and update. - A change in one class can potentially break functionality in any classes that depend on it. - Strategic Goal: Keep objects "loosely coupled" and as independent as possible.
D.1.8 — Constructing Related Objects - Examination requirements: Be able to construct definitions for up to objects and explain their relationships. - Requirements for Class Definitions: Always include attributes (with explicit types), the constructor, and relevant accessors/mutators.
D.1.9 — Data Types - Correct data types are essential for valid calculations and storage. -
int: Used for whole numbers, counts, and array indices (e.g.,employeeID,fyCount). -double: Used for decimal values such as prices, salaries, and tax rates. -String: Used for names, codes, and general text. -boolean: Used fortrue/falseconditions or flags. - Errors: Incorrect types prevent arithmetic (e.g., multiplying a String) or cause program errors.D.1.10 — Parameters and Methods - Parameters: Used to pass data INTO methods. In IB CS SL, this follows "pass-by-value" rules, meaning a copy of the value is passed and the original remains unchanged. - Scope: Parameters only exist within the specific method where they are defined (local scope). - Returns: Methods can return at most one value using the
returnkeyword. Avoidmethod returns nothing.
D.2 — Features of Object-Oriented Programming (OOP)
D.2.1 — Encapsulation - The process of bundling data (attributes) and actions (methods) together within one object. - Includes controlling external access via access modifiers (
private,protected,public). - Data is hidden; external code must interact with internal data only through defined methods.D.2.2 — Inheritance - A child (sub) class inherits all attributes and methods from a parent (super) class using the
extendskeyword in Java. - The child class can add its own specific attributes and methods. - Super Constructor: Thesuper(...)call is used in the child constructor to invoke the parent constructor. - SL Limitation: Multiple inheritance (inheriting from more than one parent) is not required for the Standard Level (SL) curriculum.D.2.3 — Polymorphism - Meaning "many forms," polymorphism allows the same method name to behave differently based on context. - Method Overloading: Occurs within the same class; multiple methods have the same name but different parameters. The specific method called depends on the inputs provided. - Method Overriding: Occurs when a subclass defines a method name that already exists in the parent class; the subclass version executes instead of the parent version.
D.2.4 — Advantages of Encapsulation - Limits the scope of data to the object, reducing unintended side effects and software bugs. - Forces the use of accessor/mutator methods, allowing for validation logic (e.g., ensuring a salary is greater than ). - Protects data integrity in team environments by preventing other programmers from directly modifying
privatedata. - Makes objects self-contained and reusable.D.2.5 — Advantages of Inheritance - Code Reusability: Child classes reuse logic without rewriting it. - Maintenance: Updating a parent class once automatically propagates changes to all child classes. - Efficiency: Reduces overall development time for common functionality. - Modeling: Natural representation of real-world hierarchies (e.g.,
Animal→Dog).D.2.6 — Advantages of Polymorphism - Allows child classes to customize behavior for specific types by overriding parent methods. - External code can call the same method name on various object types without needing implementation details. - High flexibility and extensibility; new subclasses can be added without modifying existing code. - Removes the need for complex conditional logic (e.g.,
if/elsechecks for object types).D.2.7 — Libraries of Objects - Libraries are collections of pre-written, reusable classes (e.g., sorting algorithms, data structures). - Advantages: Saves time, code is widely tested (fewer bugs), and promotes abstraction (using logic without knowing the internal implementation). - Example:
import java.util.Arrays;in Java.D.2.8 — Disadvantages of OOP - Can be overly complex for simple or small tasks due to the overhead of setting up classes. - Not ideal for sequential or procedural tasks. - Risk of "over-engineering" through unnecessary hierarchy or abstraction. - Steeper learning curve compared to procedural programming.
D.2.9 — Programming Teams - OOP facilitates team development because programmers can work on separate classes independently. - Allows for parallel work and specialization (testers, documenters, front-end vs. back-end). - Information Hiding: Reduces dependencies between modules created by different team members. - Requirement: Necessitates agreed-upon naming conventions and coding standards.
D.2.10 — Modularity - Breaking programs into smaller, independent modules/classes. - Benefits: Easier to debug (isolate modules), easier to test (unit testing), and allows for parallel development and high reusability.
D.3 — Program Development and Java Syntax
D.3.1 — Key Data Terms - Identifier: The specific name assigned to a variable, method, or class (e.g.,
salary,Employee). - Primitive: Built-in basic data types likeint,long,double,char,boolean. - Instance Variable: An attribute declared inside the class but outside any method; every object has an independent copy. - Parameter Variable: Passed into a method during a call; exists only within that method. - Local Variable: Declared inside a method; exists only for the duration of the method call.D.3.2 — Key Action Terms - Method: A named block of code defined inside a class. - Accessor: A "get" method; used to read and return a private attribute without changing it. - Mutator: A "set" method; used to change a private attribute's value, often including validation logic. - Constructor: A special method reflecting the class name; called during instantiation to initialize attributes. - Signature: The combination of a method's name and its parameter list (e.g.,
addComplaint(String complaint)); identifies the method for overloading. - Return Value: The data sent back by a method; specified by the return type (orvoid).D.3.3 — OOP Keywords in Java -
private: Access restricted to the class itself. -protected: Access for the class and its subclasses. -public: Access from anywhere. -extends: Used to establish inheritance. -static: Indicates the member belongs to the class itself, not instances; shared across all objects; can be called without instantiation. -this: References the current object; used to differentiate instance variables from parameters of the same name.D.3.4 — Primitive Types vs. Strings -
int: Whole numbers (e.g., , ). -long: Large whole numbers. -double: Real/decimal numbers (e.g., , ). -char: A single character (e.g., 'A'). -boolean:trueorfalse. -String: A reference type (not primitive); a class representing a sequence of characters, written with a capital S.D.3.5–D.3.8 — Code Construction Examples - Constructor with Array Initialization: -
public Employee(String name, int employeeID, double salary) {-this.name = name;-this.employeeID = employeeID;-this.salary = salary;-this.complaints = new String[10];-}- Accessor and Mutator with Validation: -public double getSalary() { return salary; }-public void setSalary(double salary) { if (salary > 0) this.salary = salary; }- Inheritance withsuperCall: -public class Salesman extends Employee { private double commissionRate;-public Salesman(String name, int id, double salary, double commRate) {-super(name, id, salary);-this.commissionRate = commRate; } }- Static Method Definition and Call: - Definition:public static double calcNetSalary(double salary, double taxRate) { return salary - (salary * taxRate); }- Call:Employee.calcNetSalary(40000, 0.25);- Array Traversal (Finding First Empty Slot): -for (int i = 0; i < array.length; i++) { if (array[i] == null) { array[i] = newItem; break; } }- Selection (If/Else): -if (salary > 0) { this.salary = salary; } else { System.out.println("Invalid salary"); }D.3.9 — Internationalisation - Modern programming languages (Java, Python, C++) utilize Unicode character encoding. - Unicode supports characters from nearly all global writing systems, moving beyond the limitations of ASCII. - This allows software to process and display text in any language, facilitating use by global teams.
D.3.10 — Ethics in Programming - Testing: Adequate testing is required before software release to prevent commercial, financial, or personal harm from bugs. - Plagiarism: It is a professional duty to acknowledge others' work and credit code sources. - Open Source Movement: Involves voluntarily sharing code for public use, modification, and improvement to promote transparency and collaboration. - Professional Responsibility: Programmers must consider the broader impact of their software on society and individual users.