0% found this document useful (0 votes)
312 views32 pages

Option D Study Guide

This document provides an overview of object-oriented programming concepts for the IB Computer Science SL/HL exam. It defines key OOP terminology like class, object, method, and inheritance. It also covers OOP principles like encapsulation, polymorphism, and abstraction. Specific programming concepts like data types, instantiation, and UML class diagrams are explained. Examples are provided to illustrate class structure and the use of methods, constructors, and access modifiers. The document is a reference for the object-oriented programming section of the IB Computer Science exam.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
312 views32 pages

Option D Study Guide

This document provides an overview of object-oriented programming concepts for the IB Computer Science SL/HL exam. It defines key OOP terminology like class, object, method, and inheritance. It also covers OOP principles like encapsulation, polymorphism, and abstraction. Specific programming concepts like data types, instantiation, and UML class diagrams are explained. Examples are provided to illustrate class structure and the use of methods, constructors, and access modifiers. The document is a reference for the object-oriented programming section of the IB Computer Science exam.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

IB Computer Science SL/HL

Paper 2 - Option D: Object-Oriented


Programming

Summary
[Click a link below to access the relevant section]

1. Vocabulary Bank
2. Data Types
3. Programming Languages, Code Quality, and Open-Source
4. OOP Overview
5. Instantiation
6. Inheritance
7. Aggregation
8. Polymorphism
9. Encapsulation
10. Static Methods & Attributes
11. UML and Relationship Diagrams
12. LinkedLists (HL)
13. 2D Arrays (HL)
14. Stacks (HL)
15. Recursion (HL)
16. Binary Search Trees (HL)

Sold 1 to
[email protected]
Vocabulary Bank
- Object - unit of data that contents variables and methods
- Class - Template (blueprint) for object including variables and methods
- Identifier - name that is used to identify a variable, method, class, or other programming
entity
- Object Reference - A variable that is used to access an object; the variable contains the
memory address of the object
- Object Instantiation - create an instance of an object from a class
- Attribute - variable or method
- Method - another word for a function - independent block of code that can be called on
to return an output given a specific range of inputs
- Method Signature - Included the name of the function and all its parameters - generally
the first line of the function
- Mutator Method - a method that is used to modify an attribute (the state) of an object
- Accessor Method - a method that is used to access and attribute (the state) of an object
- Method Overriding - feature that allows a subclass to provide a different implementation
of a method that is already defined in its superclass
- Method Overloading - a feature that allows for different implementations of a method in
the same class
- Polymorphism - a concept in object-oriented programming (OOP) that allows objects of
different types to be treated as if they were of the same type
- Encapsulation - refers to the idea of bundling data and methods that operate on that data
within a single unit, known as a class
- Aggregation - a type of relationship between objects in Java where one object contains
one or more instances of another class as part of its own internal state
- UML (Uniform Modeling Language) Diagram - Used to describe the structure of a system,
including its classes, attributes, and relationships
- Modularity - the practice of organizing code into smaller, independent units, known as
modules or packages.
- Access Modifier - control the level of access that other parts of the program have to a
particular class, method, or variable
- Inheritance - allows one class to inherit the properties and behaviors of another class
- Constructor - a special method that is called when an object of a class is created;
initializes the object's instance variables and prepares it for use.
- Dependency - where one class depends on another class to perform its functionality -
i.e. a Car object must have an Engine object

2
Data Types

Data Type Description Example

byte Represents an 8-bit integer byte age = 21;

int Represents a 32-bit integer int count = 100;

long Represents a 64-bit integer long population =


9876543210L;

double Represents a double-precision double pi =


floating point number 3.141592653589793;

char Represents a single character char grade = 'A';

boolean Represents a boolean value boolean isRaining =


(true or false) true;

String Represents a sequence of String message =


characters (a string) "Hello, World!"

Programming Languages, Code Quality, and Open-Source


- Modern Programming Languages
- Examples include Java, C++, Python
- Features
- Use of Unicode
- Portability (Can be used on different machines and OSes)
- Abstraction - hides the underlying details of how the programming
language works
- Leads to expressive and easy to read code
- Allows for the use of paradigms like object-oriented programming
to mimic real-like processes
- Automatic Memory Management - Programmers don't have to worry about
manually allocating memory for variables, methods, etc.
- Code Quality
- A hallmark of a productive programmer
- Examples of high code quality: indentation, comments, meaningful variable,
method, and class names

3
- Benefits
- Easier for other programmers to understand your work
- Easier to debug consistent, commented code
- Easy for other programmers to maintain your code
- Open-Source Code - refers to software code that is made available to the public
and released under a license that grants users the right to view, modify, and
distribute the code.

Pros Cons

Accessibility - Open-source code is Lack of Vendor Support - Open-source


freely available, allowing users to software may not come with official
access and use the software without vendor support, leaving users to rely
restrictions on community support or self-help
resources.

Cost Savings - Open-source software Security Risks - While transparency


eliminates the need for expensive can enhance security, open-source
licensing fees software may also be susceptible to
security vulnerabilities if not properly
maintained or if malicious code is
introduced.

Customization & Flexibility:


Open-source code allows users to
modify and customize the software to
meet specific needs

4
OOP (Object-Oriented Programming) Overview
- OOP (Object-Oriented Programming)
- OOP is a method of organizing information in a computer program that seeks to
model the real world.
- It organizes data by category.
- Objects represent a unit of data that can be passed around a program
- A class is a template from which an object is created and determines whether
information needs to be in the object.
- Each object has variables and functions associated with it called attributes and
behaviors, respectively.
- OOP Pros & Cons

5
Anatomy of a Class

public class Employee {


// Attributes/Properties/Member Variables/Instance Variables/Class
Variables
private String name;
static double taxRate = .3;
private int employeeId;
private double salary;
protected String[] complaints;

// Constructor method (same name as class, no return type)


public Employee(String name, int employeeId, double salary) {
this.name = name;
this.employeeId = employeeId;
this.salary = salary;
this.complaints = new String[10];
System.out.println("New object created");
}
// Methods, Functions, Behaviors
// Mutator method
public void addComplaint(String complaint) {
for (int i= 0; i < complaints.length; i++) {
if(complaints[i] == null) {
complaints[i] = complaint;
break;
}
}
}
// Accessor method
public String[] getComplaints() {
return this.complaints;
}
// Mutator method
public void setSalary(double salary) {
if(salary > 0) {
this.salary = salary;
}
}
// Accessor method
public double getSalary() {
return salary;
}
...
}

6
Instantiation
- Instantiation
- The act of creating an object from a template
- The constructor is invoked in the process
- Constructor - a special method that is used to initialize an instance of a class
- When a new instance of a class is created, the constructor method is
automatically called to initialize the object and prepare it for use
- Has the same name as the class itself
- Does not have a return type
- May take parameters to allow the caller to provide initial values for the object's
properties

7
Instantiation (Example)

public class Employee {


private String name;
static double taxRate = .3;
private int employeeId;
private double salary;
protected String[] complaints;

// Constructor method
public Employee(String name, int employeeId, double salary) {
this.name = name;
this.employeeId = employeeId;
this.salary = salary;
this.complaints = new String[10];
System.out.println("New object created");
}

public void addComplaint(String complaint, String transactionId) {


for (int i= 0; i < complaints.length; i++) {
if(complaints[i] == null) {
complaints[i] = complaint.concat(transactionId);
break;
}
}
}

...
}
// Instantiation
Employee employeeOne = new Employee("Walter", 356, 1000000);
// Example of object method usage
employeeOne.addComplaint("Scarily smart.");

8
Instantiation (Diagram)

Inheritance
- Inheritance
- Allows new classes to be created based on existing classes, thus inheriting their
properties and behavior
- Existing class is called the superclass or parent class, and the new class is called
the subclass or child class
- extends keyword is used to create a subclass of a superclass
- Inheritance Pros & Cons

9
Inheritance (Example)

public class Employee {


private String name;
static double taxRate = .3;
private int employeeId;
private double salary;
protected String[] complaints;

public Employee(String name, int employeeId, double salary) {


...
}

public void setSalary(double salary) {


if(salary > 0) {
this.salary = salary;
}
}
...
}

public class Salesman extends Employee {


private double commissionRate;
private double totalSalesValue;
private Sale[] sales;

public Salesman(String name, int employeeId,


double salary, double commissionRate) {
super(name, employeeId, salary);
this.commissionRate = commissionRate;
this.totalSalesValue = 0;
this.sales = new Sale[10];
}

...
}

Salesman salesmanOne = new Salesman("Tuco", 666, 500000, .75);


salesmanOne.setSalary(1000000);

10
Inheritance (Diagram)

11
Aggregation
- Aggregation
- A relationship between classes where one class contains an instance of another
class as a member variable
- When that class is instantiated, we end up with an object that contains other
objects
- If the “container object” is destroyed, the “contained object” will still exist
- Inheritance vs. Aggregation

12
Aggregation (Example)

public class Salesman extends Employee {


private double commissionRate;
private double totalSalesValue;
private Sale[] sales;

public Salesman(String name, int employeeId,


double salary, double commissionRate) {
super(name, employeeId, salary);
this.commissionRate = commissionRate;
this.totalSalesValue = 0;
this.sales = new Sale[10];
}

public void addSale(Sale sale) {...}

public Sale[] getSales() {...}

public class Sale {


private String transactionId;
private double saleValue;
private String buyerName;

public Sale(String transactionId, double saleValue, String


buyerName) {
this.transactionId = transactionId;
this.saleValue = saleValue;
this.buyerName = buyerName;
}
...

Salesman salesmanOne = new Salesman("Tuco", 666, 500000, .75);


Sale sale = new Sale("988790", 1000, "Emilio");
// Sale object is added to sales array of Salesman object
(salesmanOne)
salesmanOne.addSale(sale);

13
Aggregation (Diagram)

14
Polymorphism
- Polymorphism
- A situation in which something can occur in different form, and we can therefore
perform the same action in many different ways
- In Java, refers to method overloading and method overriding.
- method overloading - situation in which there are different methods in the
same class with the same name, but which have different parameters
- method overriding - situation in which there are different methods in the
superclass and subclass with the same name, but which have different
parameters
- These can all be used, with parameters being the distinguishing factor.

Method Overloading (Example)

public class Employee {


private String name;
static double taxRate = .3;
private int employeeId;
private double salary;
protected String[] complaints;

public Employee(String name, int employeeId, double salary) {


...
}

public void addComplaint(String complaint) {


...
}

public void addComplaint(String complaint, String complaintId) {


...
}
}

Employee employeeOne = new Employee("Walter", 356, 1000000);


employeeOne.addComplaint("Scarily smart.");
employeeOne.addComplaint("Scarily smart.", "XLM3");

15
Method Overriding (Example)

public class Employee {


...

public Employee(String name, int employeeId, double salary) {


...
}

public void addComplaint(String complaint) {


...
}

...
}

// Salesman is a subclass of Employee


public class Salesman extends Employee {
...

public Salesman(String name, int employeeId,


double salary, double commissionRate) {...}

...

public void addComplaint(String complaint, String transactionId) {


...
}
...
}

Salesman salesmanOne = new Salesman("Tuco", 666, 500000, .75);


// Method on Employee class
salesmanOne.addComplaint("Insane");
// Method on Salesman class
salesmanOne.addComplaint("Insane", "988790");

16
Encapsulation
- Encapsulation
1) the technique of binding data and functions together in a single unit (class) and
controlling access to that unit from outside
2) refers to the practice of hiding the internal details of an object from the outside
world
- Access modifiers
- Used to control access to attributes, methods, constructors, and sometimes,
classes
- private - can only be accessed and modified from within the same class in which
it was defined, and cannot be accessed from outside the class, including by
instances of that class
- protected - an be accessed and modified from within the same class in which it
was defined, as well as by any subclass of that class
- public - can be accessed and modified by any code that has a reference to an
instance of the class, as well as from within the class itself

17
Static Methods & Attributes
- Static Methods & Attributes
- Means that the method or attribute is the same for all instances of a class
- Defined the class level
- Contained in the classes rather an instance of the class (object)
- Less memory is taken up because memory is allocated for only one instance,
rather than every objects

Static Methods & Attributes (Example)

public class Employee {


private String name;
// Static attribute
static double taxRate = .3;
private int employeeId;
private double salary;
protected String[] complaints;

public Employee(String name, int employeeId, double salary) {...}


...
// Static method
public static double calculateNetSalary(double salary, double
taxRate) {
double taxableIncome = salary*(1-taxRate);
double netSalary = salary - taxableIncome;
return netSalary;
}

// No instantiation is required to use static methods/attributes


double saulsSalary = Employee.calculateNetSalary(40000, .25);
System.out.println(Employee.taxRate);

18
UML (Uniform Modeling Language) Diagrams
- Classes - Contains 3 components
1) Class Name
2) Attributes
3) Behaviors (Methods)

19
- Relationships Diagram - Describes the relationship between classes/objects in a program

20
LinkedLists (HL)
- LinkedLists
- Java-specific data structure
- Doubly-linked list (although sometimes referred to as a singly-linked list on the
exam)
- Each piece of data is stored in a node, with pointers
- Located non-contiguously in memory - addresses of nodes are spread out across
RAM and nodes only linked by pointers
- Ideal for frequent insertion or deletion of elements, or when the size of the list is
unknown
- Ideal Use Cases
- Implementing a Queue - front of the queue is represented by the head of
the Linked List, and the rear of the queue is represented by the tail of the
Linked List.
- Implementing a Stack - top of the stack is represented by the head of the
Linked List, and the bottom of the stack is represented by the tail of the
Linked List
- Large Data Sets (due to dynamic memory allocation)

Example 1: Create and Initialize LinkedList

LinkedList<Student> studentList = new LinkedList<>();


Student jamesObject = new Student("John Doe", 20, "Computer Science",
85);
Student janeObject = new Student("Jane Smith", 21, "Mathematics",
90); // Add 5 Student objects to the list
studentList.add(jamesObject);
studentList.add(janeObject);
studentList.add(new Student("Bob Johnson", 19, "Physics", 92));
studentList.add(new Student("Alice Brown", 22, "Chemistry", 88));
studentList.add(new Student("Charlie Lee", 18, "Biology", 87));

21
Example 2: Display Contents of Linked List

public void displayStudentInfo(LinkedList<Student> studentList) {


int index = 0;
while(index < studentList.size()) {
Student currentStudent = studentList.get(index);
System.out.println(currentStudent.getName() + " "+
currentStudent.getGrade());
index++;
}
}

Example 3: Transfer Contents of an Array to a Linked List

public LinkedList<Student> arrayToLinkedList(Student[] studentArray)


{
LinkedList<Student> studentList = new LinkedList<>();
for(int i = 0; i < studentArray.length; i++) {
studentList.addLast(studentArray[i]);
}
return studentList;
}

Example 4: Transfer Contents of a LinkedList to an Array

public Student[] linkedListToArray(LinkedList<Student> studentList) {


Student[] studentArray = new Student[studentList.size()];
int studentArrayIndex = 0;
while(studentArrayIndex < studentList.size()) {
studentArray[studentArrayIndex] =
studentList.get(studentArrayIndex);
studentArrayIndex++;
}
return studentArray;
}

22
Example 5: Transfer Contents of a LinkedList to an Array (Using an Iterator)

public Student[] iteratorlinkedListToArray(LinkedList<Student>


studentList) {
Student[] studentArray = new Student[studentList.size()];
int studentArrayIndex = 0;
ListIterator<Student> studentIterator =
studentList.listIterator();
while (studentIterator.hasNext()) {
studentArray[studentArrayIndex] = studentIterator.next();
studentArrayIndex++;
}
return studentArray;
}

Example 6: Find the Maximum Value of An Attribute in a LinkedList of Objects

public int findMaximum(LinkedList<Student> studentList) {


int maximum = studentList.getFirst().getGrade();
ListIterator<Student> studentIterator =
studentList.listIterator();
while(studentIterator.hasNext()) {
Student currentStudent = studentIterator.next();
int currentGrade = currentStudent.getGrade();
if(currentGrade > maximum) {
maximum = currentGrade;
}
}
return maximum;
}

23
Example 7: Remove an Object Based on Some Criteria

public boolean removeByName(LinkedList<Student> studentList, String


name) {
int index = 0;
while(index < studentList.size()) {
Student currentStudent = studentList.get(index);
if (currentStudent.getName() == name) {
studentList.remove(index);
return true;
}
}
return false;
}

Linked Lists Pros & Cons

24
ArrayLists vs. LinkedLists

Feature ArrayList LinkedList

Data Structure Dynamic array (as opposed to Doubly linked list


static arrays seen so far in IB)

Access Faster than LinkedLists - Slower than ArrayLists - need


element can be accessed at to iterate through LinkedList
index until element is found

Insertion/Deletion Slower than LinkedLists - Faster than ArrayLists -


blocks of memory need to be pointers simply need to be
moved to accommodate new changed to accommodate
element new element

Memory Contiguous (next to each Non-contiguous memory


other in RAM) block of
memory

Usage Ideal for random access of Ideal for frequent insertion


elements and when the and deletion of elements, or
number of elements is known when the number of elements
in advance is unknown

25
Recursion (HL)
- Tips for Using Recursion
1. Understand that recursion is used when we are repeating the same behavior with
consistently changing parameters.
2. Model the problem with an example input and output.
3. Turn the problem into a set of individual steps.
4. Keep in mind that at least one of the function parameters is going to have to
change on each recursive function call.
5. Understand that the base case is where the recursive calls will stop - it effectively
stops the function from calling itself
- Recursion Pros & Cons

- Ideal Use Cases


1. Traversing tree-like data structures: Recursion is ideal for traversing tree-like data
structures, such as Binary Search Trees or file systems. The recursive function can
be called on each node of the tree, allowing you to visit all of the nodes in a
structured and efficient way.
2. Solving mathematical problems: Many mathematical problems can be solved using
recursion, such as the Fibonacci sequence or the Tower of Hanoi puzzle.
Recursion can be used to break the problem down into smaller sub-problems,
which can be solved recursively until the final solution is reached.

26
2D Arrays (HL)
Example 1: Initializing and Creating a 2D Array
int[][] grades = {{99, 75, 68, 21, 98},
{100, 89, 73, 55, 77},
{100, 45, 99, 89, 71},
{99, 75, 89, 99, 100},
{89, 100, 54, 65, 99}};

Example 2: Display Contents of 2D Array


public static void outputGrades(int[][] grades) {
for(int i = 0; i < grades.length; i++) {
for(int j = 0; j < grades[i].length; j++) {
System.out.println(grades[i][j]);
}
}
}

Example 3: Calculate Average of Integers in a 2D Array


public static double getAverageGrade(int[][] grades) {
int sum = 0;
int count = 0;
for (int i = 0; i < grades.length; i++) {
for (int j = 0; j < grades[i].length; j++) {
sum = sum + grades[i][j];
count++;
}
}
double average = sum/count;
return average;
}

- Ideal Use Cases


- Images - Each image is split into a grade, which is represented by a 2D array; Each
element is a pixel
- Games (i.e. game map or game board)
- Large data sets - used to represent a table of data

27
Stacks (HL)
Example 1: Create and Initialize Stack

// Create a new Stack object to hold Student objects


Stack<Student> studentStack = new Stack<>();
// Add 5 Student objects to the stack
studentStack.push(new Student("John Doe", 20, "Computer Science",
85));
studentStack.push(new Student("Jane Smith", 21, "Mathematics", 90));
studentStack.push(new Student("Bob Johnson", 19, "Physics", 92));
studentStack.push(new Student("Alice Brown", 22, "Chemistry", 88));
studentStack.push(new Student("Charlie Lee", 18, "Biology", 87));

Example 2: Display Contents of Stack

public static void displayStack(Stack<Student> students) {


Stack<Student> temp = new Stack<>();
while(!students.isEmpty()) {
Student currentStudent = students.pop();
System.out.println(currentStudent.getName()+ " " +
currentStudent.getGrade());
temp.push(currentStudent);
}
while(!temp.isEmpty()) {
students.push(temp.pop());
}
}

28
Example 3: Filter Out Contents of Stack By Some Criteria

public static void transferHighGrades(Stack<Student> students,


Stack<Student> empStack) {
while(!students.isEmpty()) {
Student currentStudent = students.pop();
if(currentStudent.getGrade() >= 90) {
empStack.push(currentStudent);
}
}
}

Example 4: Remove Specific Object From Stack Based on Some Criteria

public static boolean removeStudent(Stack<Student> students,


String name) {
boolean found = false;
Stack<Student> temp = new Stack<>();
while (!students.isEmpty()) {
Student currentStudent = students.pop();
String currentName = currentStudent.getName();
if (currentName != name) {
temp.push(currentStudent);
} else {
found = true;
}
}
while(!temp.isEmpty()) {
students.push(temp.pop());
}
return found;
}

29
- Ideal Use Cases
- Undo/Redo functionality - Any action that is done in an application is pushed on to
a stack and can be popped to undo and action or pushed again to redo an action
- Expression evaluation - Each time a new operator or operand is encountered, it is
pushed onto the stack. When an operator is encountered, the operands are
popped off the stack, the operation is performed, and the result is pushed back
onto the stack.
- Function call stack - Each time a function is called, its parameters and local
variables are pushed onto the stack. When the function returns, the values are
popped off the stack and control returns to the calling function.

Binary Search Trees (HL)


Node Class (Used in IB Example and Examples to Follow)

public class Node {


Node left;
Node right;
int data;
Node(int newData) {
left = null;
right = null;
data = newData;
}
}

30
Example 1: Creating and Initializing a Binary Tree

Node treeRoot = new Node(50);


Node leaf1 = new Node(25);
Node leaf2 = new Node(75);
Node leaf3 = new Node (19);
Node leaf4 = new Node(27);
Node leaf5 = new Node(78);
Node leaf6 = new Node(21);
treeRoot.left = leaf1;
treeRoot.right = leaf2;
leaf1.left = leaf3;
leaf1.right = leaf4;
leaf2.right = leaf5;
leaf3.right = leaf6;
Node targetNode = findValue(treeRoot, 19);

Example 2: Display the Contents of a Binary Tree

public void outputTree(Node root) {


if (root==null) {
Return;
}
// Simply need to access and conduct operation
// No need to return value
outputTree(root.left);
outputTree(root.right);
System.out.println(root.data + " ");
}

Example 3: Find the Minimum Value in a Binary Tree (of Integers)


public static int findMinimum(Node root) {
if(root.left == null) {
return root.data;
} else {
return findMinimum(root.left);
}
}

31
- Binary Search Trees Pros & Cons

- Ideal Use Cases


- 1. Sorting: BSTs can be used for sorting elements, where each element is stored
as a node in the tree. The elements can be sorted by performing an in-order
traversal of the tree, which will visit the nodes in ascending order.
- 2. Unique elements: BSTs are useful for maintaining a collection of unique
elements, as duplicate elements are automatically discarded when they are
inserted into the tree.
- 3. Database indexing: BSTs can be used for indexing database tables, where each
row in the table is stored as a node in the tree. This allows for efficient searching
and sorting of the data.

32

You might also like