IB Computer Science Unit 1
IB Computer Science Unit 2
IB Computer Science Unit 3
IB Computer Science Unit 4
IB Computer Science Unit 5
IB Computer Science Unit 6

IB Computer Science Encapsulation of Data

IB Computer Science Learning Goals

In this IB Computer Science lesson you will be learning about:

  • Using classes that combine data and methods

What is Encapsulation?

In the last lesson you looked at creating an object with only data. You could refer to this data as the attributes or characteristics of the object.

Sometimes the objects you want to create might also have behaviors associated with them. In object oriented programming you encapsulate (combine and hide) the attributes and behaviours together in one class.

Example: Fraction Objects

Suppose you wanted to create a new data type to represent a rational number (a fraction)

Attributes:

  • Numerator
  • Denominator

Behaviors:

  • Add, Subtract, Multiply, Divide
  • Convert to Decimal
  • Convert to Mixed Fraction\
  • Convert to Improper Fraction
  • Convert to Lowest Terms
  • Display in form n/d

Example: Phone Book Objects

Suppose you wanted to create a new data type to a phone book

  • Attributes
    • FirstName, Last Name
    • Phone #
    • Address
  • Behaviours
    • Add, delete
    • Change Info, lookup info
    • Sort information
    • display information

Example: Space Ship in a Game

Suppose you were making a game and created a space ship for the player to control

  • Attributes
    • Health, lives
    • speed, position
  • Behaviours
    • Change Position
    • Add/Remove Lives
    • Add/Remove Health
    • Check collisions with enemy
    • Fire a weapons

 

What makes up an Encapsulated Class?

Just as with basic data objects, the attributes are represented as variables, but the behaviours will be represented as methods in your class.

There are different types of methods that “could” be contained in your Class.

Constructors

  • These define how a programmer can create the object in another program
  • They usually set the value of the attributes to some initial value

Accessor and Mutator Methods

  • Accessors retrieve the information stored in the attributes (sometimes they are called “getters”)
  • Mutators modify the information stored in the attributes (sometimes they are called “setters”)
    Behaviour Methods
  • Carry out the required behavior for the object

Helper Methods

  • Background tasks that assist in carrying out the behaviors

 

Designing a Bank Account Class

In the Rest of this note we will be looking at the following example about a Bank

You have been given a task by a Bank to help write some software to create bank accounts for their customers. The bank needs to be able to create accounts with the customers name and an initial balance. Bank employees will need to be able to deposit money into the account, withdraw money from the account, and display the current balance of the account

What fields are necessary?

  • A variable to store the name of the owner -> Should be a String
    A variable to store the amount of money in the account -> Should be a double

What Constructors are necessary?

  • Need to set the name of the owner and the initial balance the owner first deposited
  • Only allow positive account balances to be entered

What Behaviors are necessary?

Deposit Method

  • No Return Value
  • Accept a double value to represent the amount of the deposit
  • Add the deposit to the existing balance
  • Check for a negative input

Withdraw Method

  • No Return Value
  • Accept a double value to represent the amount of the withdrawal
  • Subtract the deposit from the existing balance
  • Check for negative input and if there is enough money in the account to withdraw

Display Method

  • Return a String representing the owners name followed by his account balance.
  • No parameters need to be passed to the function

 

Creating the Fields

The fields can be declared in the same way they were for data objects, except for one thing. You need to ask yourself as the programmer of the class if another programmer using your class should be able to access those fields directly using object.name notation or should they be hidden from that programmer and only allow access through methods where you have control over what values are acceptable. Generally speaking you should always hide your fields from other users. To accomplish this task you should declare them as private variables instead of public variables.

In Our bank example the code would be written as follows

IB Computer Science Java Encapsulation Fields

Creating the Constructor

A constructor is a way to tell the user of the class how to create objects.

  • The name of the constructor method MUST be the same as the Class.
  • Its name should be capitalized just like the class name.
  • It does not have a return value, but it can accept parameters as inputs.
  • If you don’t specify a Constructor Methods, then your class will still work using the default constructor that Java always creates. I will illustrate this below.

In our bank example the constructor will accept 2 parameters as inputs, which represent the owner and the initial balance of the bank account. So inside the method you will have to assign the field values to the input parameters.

Here are two possible ways of doing this in Java

IB Computer Science Java Constructor Create

There isn’t any real difference between them except with the first method you use the keyword “this” in front of the field name.

  • The “this” keyword refers to the current object, so its using objectName.field notation to refer to field variables
  • We will see more of the “this” notation later on in the lesson

You might ask why bother to do that? Well if the first method I used the variables in the parameters as the same variable name as the fields in the class. This was done for readability sake. So I couldn’t make a statement like owner = owner as the program wouldn’t know that the first owner referred to the class variable and the second owner referred to the parameter variable. Adding the “this” notation clears it up for the compiler. In the second method I just avoided having the same variable name in my parameters. Its not ideal as it might not be clear what I’m actually trying to pass from the constructor.

Using the constructor

Now that you have defined in the class how Account objects will be created, here would be an example of how to use them in another program

IB Computer Science Java Creating Objects

This code will create two different bank accounts:

  • An account was created with the owner “Paul Rogers” with an initial balance of $4500
  • An account was created with the owner “Kristyn Jones” with an initial balance of $3500

If you tried to create a new account as follows, then an error message would be generated for the bank employee and it would still create the account but with an opening balance of $0.

IB Computer Science Constructor

It is possible to define more than one Constructor for your class, that allows objects to be created in different ways, but we will revisit that concept in a later lesson.

Creating the Behavior Methods

The Behaviour Methods are created just like any other method in Java except you don’t need to add the keyword static anymore. That is because methods don’t need to be static when being called by objects.

IB Computer Science Bank Account Withdraw
IB Computer Science Bank Account Display

Using Behavior Methods

To call methods from objects we use the objectName.methodName notation.

IB Computer Science Java calling class methods

Robot Example

You are writing some code to control a simple robot as it goes on an adventure.

Details of the Robot:

  • The robot has a home base
    • It can only move in a one dimensional straight line (LEFT OR RIGHT) from its home base
  • The robot can move at different speeds during its adventure
  • The robot can start its adventure at any position from its home but it never has any initial speed at the beginning.
  • The robot can have a maximum speed of 30 cm / s.

Let’s create a class to represent this robot and then write a test program that gets the robot to move. There are multiple ways to design the class, here is one potential solution

Fields

  • Position -> The distance in cm from the home base in cm.
    • Positive if the robot is to the right of the home base
    • Negative if the robot is to the left of the home base
  • Speed -> Can only be a positive number

Constructor:

  • Accept the starting position of the robot as the only parameter
    • This position could take both positive or negative values (see field details)
  • Always set the speed to 0

Behaviors

Move Right

  • Accept as a parameter how long in seconds to move the robot to the right
  • New position = old position + speed * time

Move Left

  • Accept as a parameter how long in seconds to move the robot to the left
  • New position = old position – speed * time

Change Speed

  • Accept as a parameter the amount to change the speed by
  • If its positive the speed gets faster
  • If its negative the speed gets slower
  • New speed = old speed + amount
  • Check if the speed exceeds the max -> set speed to 30
  • Check if the speed goes negative -> set speed to 0

Display Location

  • Show the location of the new object as the amount of cm right or left from the home base

Robot Class

Here is what that completed class might look like

IB Computer Science Robot Class
IB Computer Science Robot Class

Test Program for the Robot

Here is a program that tests the Robot class we just created
Output:

IB Computer Science Robot Class Test Program

You should check the math to make sure that this output makes sense.

IB Computer Science Robot Class Output

Combining Classes

Suppose you were asked to write a program that could find the area and perimeter of triangle if you were given the vertices of that triangle

Design:
The vertices are Points in Two Dimensions so we can design a Point Class and then use those Point objects as inputs to a Triangle Class
Point Class

Fields:
• x and y values to represent the 2D coordinates (use int to keep things simple)
Methods:
• Fields are private so we might need Getter Methods for the fields

IB Computer Science Point Class Java

Triangle Class

Fields
• 3 Point objects to represent the Vertices

Methods
• Area Method -> no parameters just return the area as a double (A,B,C) are vertices in the formula
• Perimeter Method -> no parameters just return the perimeter as a double
• Side Length -> private Helper method that calculates the side lengths for the perimeter

IB Computer Science Triangle Class Java

Testing

IB Computer Science Triangle Class Testing

Passing objects to Methods and Returning Objects From Methods

In Physics there are physical quantities that have just a size associated with them like time, mass, and volume. However there are also quantities that have a direction associated with them. Things like position, velocity, acceleration, Force. Quantities that have both a size and a direction are called vectors. It should also be noted that with a vector the size is often called its magnitude

It is important in science to be able to know how to add numbers that have directions associated with them. For example here are some one dimensional vector math equations

IB Computer Science 2D Vector Class Output

The easiest way to think about the calculations above are to think as all vectors that are pointing to the right as positive numbers and all vectors that are pointing to the left as negative numbers.

We are going to design a Vector object that can add and subtract vector quantities in 1 dimension.

Fields

  •  Each vector will have two attributes its magnitude and direction
  • It will also have another field that will represent all numbers that point right as positives and all numbers that point left negative
IB Computer Science Vector Class 1
IB Computer Science Vector Class 2

Constructor

  • Accept the magnitude and direction as input parameters and check for valid inputs
IB Computer Science Vector Class Java Constructor

Methods

IB Computer Science Vector Class Methods

Test Program

The program below will produce the output given in the example at the start of the section

Complete the following as Practice

1. Create a Class to represent a Circle and write a test program to test to see if it works. Don’t worry about input validation in any of these practice programs. Assume the user will only input the right data to the method
Fields:
• Radius
Constructor:
• Accept the radius as a parameter
Methods:
• getArea -> returns the area of the circle
• getCircumference -> returns the circumference of the circle

2. Create a Class to represent a Rectangle and write a test program that reads 10 rectangles from a data file and outputs the Area and Perimeter of each rectangle. Design the Fields, Constructor, Methods yourself for the Rectangle Class. Don’t worry about input validation in any of these practice programs. Assume the user will only input the right data to the method

3. Create a Date class to represent a Date object. Check input validation and write a test program.
Fields:
• Day, month, year
Constructor:
• Accept all the fields as a parameters
Methods:
• getDay – returns day
• getMonth – returns the month
• getYear – returns the year
• setDay – sets the month
• setMonth – sets the day
• setYear – sets the Year
• setDate – sets all fields
• display – use format dd/mm/yyyy

 

4. Write a new Circle class called GeometricCircle that still the center point and the radius as fields. Accept two points in the constructor, the first point is the center of the circle and the second point is any other point on the circle. It should be able to calculate the area and perimeter of the circle. Test Your program.

Looking to Learn More about Computer Science and Coding?

Check out our programing in python courses that focus on high school level coding.  

  • Grade 11 Computer Science ICS3U
  • Grade 12 Computer Science ICS4U

These courses are complete with interactive coding lessons, teacher led videos, and more practice questions with complete solutions

Return To International Baccalaureate Computer Science Main Page