SSK 3101 COMPUTER
PROGRAMMING II
Topic 1 Introduction
Dr. Nor Fazlida Mohd Sani
Department of Computer Science
Faculty of Computer Science and Information Technology
University Putra of Malaysia
Room No: C2.04
Learning Objectives
• At the end of this chapter, you will be able
to:
• Describe classes and objects in OOP (A1,
C1)
• Analyze a problem using object-oriented
analysis. (C4)
• Construct a simple object-oriented
program (P4)
2
Topic 1 Introduction
SSK3101 Computer
Chapter 1 Outline
3
1. Introduction
This chapter will cover the following
topics:
1.1 Object-oriented Programming Concepts
Objects
Classes
1.2 Constructors
1.3 Constructing Objects Using Constructors
1.4 Accessing Objects via Reference Variables
1.5 Array of Objects
1.6 Class Abstraction and Encapsulation
1.7 Visibility Modifiers
1.8
Passing Objects to Methods
Topic 1 Introduction
SSK3101 Computer
1.1 Object-oriented
Programming Concepts
Objects
Object-oriented programming (OOP) involves programming using
objects.
An object represents or an abstraction of some entity in the real
world that can be distinctly identified.
For example, a student, a desk, a circle, a button, a cow, a car,
a loan, and etc.
An object may be physical, like a radio, or intangible, like a song.
Just as a noun is a person, place, or thing; so is an object
An object has a
Unique identity
State or characteristics or attributes, and
Action or behaviors.
Specifically, an object is an entity that consists of:
A set of data fields (also known as properties or attributes)
with their current values.
5
A set of methods that use or manipulate the
data
(the
SSK3101
Computer
Topic 1 Introduction
Objects – Example 1.1
Class Name: Circle
A class
templates
Data Fields:
radius is
______
Methods:
getArea()
Three objects
of class Circle
Circle Object 1
Circle Object 2
Circle Object 3
Data Fields:
radius is 10
Data Fields:
radius is 25
Data Fields:
radius is
125
An object has both a state and behavior.
The state defines the object, and the
behavior defines what the object does.
6
Topic 1 Introduction
SSK3101 Computer
Objects – Example 1.2
7
A remote control unit is an object.
A remote control object has three attributes:
The current channel, an integer,
The volume level, an integer, and
The current state of the TV, on or off, true or false
Along with five behaviors or methods:
Raise the volume by one unit,
Lower the volume by one unit,
Increase the channel number by one,
Decrease the channel number by one, and
Switch the TV on or off.
Topic 1 Introduction
SSK3101 Computer
Objects – Example 1.2 (Cont.)
Three different remote objects, each with a unique
attribute values (data) but all sharing the same methods
or behaviors.
8
Topic 1 Introduction
SSK3101 Computer
The remote control unit exemplifies encapsulation.
Encapsulation is defined as the language feature
of packaging attributes and behaviors into a
single unit.
Data and methods comprise a single entity.
Each remote control object encapsulates data
and methods, attributes and behaviors.
An individual remote unit, an object, stores its
own attributes – channel number, volume level,
power state – and has the functionality to
change those attributes.
9
Topic 1 Introduction
SSK3101 Computer
Objects – Example 1.3
10
A rectangle is an object.
The attributes of a rectangle might be length and width,
two floating point numbers; the methods compute and
return area and perimeter.
Each rectangle has its own set of attributes; all share the
same behaviors
The three rectangle objects
Topic 1 Introduction
SSK3101 Computer
Classes
Class is a template or blueprint, from which objects of
the same type are created.
A Java class uses
variables to define data fields and
methods to define behaviors.
Additionally, a class provides a special type of methods,
known as constructors, which are invoked to construct
objects from the class.
class Circle {
/** The radius of this circle */
double radius = 1.0;
Data field
/** Construct a circle object */
Circle() {
}
/** Construct a circle object */
Circle(double newRadius) {
radius = newRadius;
}
/** Return the area of this circle */
double getArea() {
return radius * radius * 3.14159;
}
}
13
Topic 1 Introduction
Constructors
Method
SSK3101 Computer
Classes – Exercise 1
Rectangle Class
A Rectangle class might specify that every Rectangle object consists of two
variables of type double:
double length, and
double width,
Every Rectangle object comes equipped with two methods:
double area(),
and //returns the area, length x width,
double perimeter(),
//returns the perimeter, 2(length + width).
Individual Rectangle objects may differ in dimension but all Rectangle objects share
the same methods
Question:
Draw a UML class diagram of rectangle class
Create a rectangle class
14
Topic 1 Introduction
SSK3101 Computer
1.2 Constructors
Constructors
• Constructors are a special kind of
methods that are invoked to construct a
new object, initialize it with the
construction parameters, and return a
• Example:
reference to the constructed object.
Circle() {
}
Circle(double newRadius) {
radius = newRadius;
}
16
Topic 1 Introduction
SSK3101 Computer
Constructors (Cont.)
A constructor with no parameters is
referred to as a no-arg constructor.
Constructors must have the same name
as the class itself.
Constructors do not have a return type—
not even void.
Constructors are invoked using the new
operator when an object is created.
Constructors play the role of initializing
objects.
17
Topic 1 Introduction
SSK3101 Computer
Default Constructor
A class may be declared without
constructors.
In this case, a no-argument constructor
with an empty body is implicitly declared in
the class.
This constructor, called a default
constructor, is provided automatically
only if no constructors are explicitly
declared in the class.
18
Topic 1 Introduction
SSK3101 Computer
1.3 Constructing Objects
Using
Constructors
Creating Objects Using
Constructors
Syntax:
new ClassName(); // default constructor
new ClassName(parameter);
Example:
new Circle();
new Circle(5.0);
20
Topic 1 Introduction
SSK3101 Computer
Declaring Object Reference Variables
To reference an object, assign the object to a
reference variable.
To declare a reference variable, use the syntax:
ClassName objectRefVar;
Example:
Circle myCircle;
21
Topic 1 Introduction
SSK3101 Computer
Declaring/Creating Objects in a Single
Step
ClassName objectRefVar = new ClassName();
Example:
Assign object
reference
Create an object
Circle myCircle = new Circle();
22
Topic 1 Introduction
SSK3101 Computer
1.4 Accessing Objects
via Reference
Variables
Accessing Objects
Data field can be accessed and its methods
invoked using the dot operator (.)
known as object member access operator.
Referencing the object’s data:
objectRefVar.data
e.g., myCircle.radius
Invoking the object’s method:
objectRefVar.methodName(arguments)
e.g., myCircle.getArea()
24
Topic 1 Introduction
SSK3101 Computer
A Simple Circle Class
25
Objective:
Demonstrate creating objects,
accessing data, and using
methods.
Topic 1 Introduction
SSK3101 Computer
1. public class TestCircle1 {
2. public static void main(String[] args) {
3. Circle myCircle = new Circle(5.0);
4. System.out.println("The area of the
circle of radius " +
5.
myCircle.radius + " is " +
6.
myCircle.getArea());
7. Circle yourCircle = new Circle();
8. System.out.println("The area of the
circle of radius "+
9.
yourCircle.radius + " is " +
10.
yourCircle.getArea());
26
Circle myCircle = new Circle(5.0);
Circle yourCircle = new Circle();
myCircl
e
no value
yourCircle.radius = 100;
28
Topic 1 Introduction
SSK3101 Computer
Trace Code, cont.
Circle myCircle = new Circle(5.0);
myCircl
e
Circle yourCircle = new Circle();
no value
: Circle
yourCircle.radius = 100;
radius: 5.0
Create a
Circle
29
Topic 1 Introduction
SSK3101 Computer
Trace Code, cont.
Circle myCircle = new Circle(5.0);
Circle yourCircle = new Circle();
myCircl reference value
e
yourCircle.radius = 100;
: Circle
Assign object
reference to
myCircle
30
Topic 1 Introduction
radius: 5.0
SSK3101 Computer
Trace Code, cont.
myCircl reference value
e
Circle myCircle = new Circle(5.0);
Circle yourCircle = new Circle();
: Circle
radius: 5.0
yourCircle.radius = 100;
yourCircl
e
no value
Declare
yourCircle
31
Topic 1 Introduction
SSK3101 Computer
Trace Code, cont.
myCircl reference value
e
Circle myCircle = new Circle(5.0);
: Circle
Circle yourCircle = new Circle();
radius: 5.0
yourCircle.radius = 100;
yourCircl
e
no value
: Circle
Create a
new Circle
object
32
Topic 1 Introduction
radius: 0.0
SSK3101 Computer
Trace Code, cont.
myCircl reference value
e
Circle myCircle = new Circle(5.0);
Circle yourCircle = new Circle();
: Circle
radius: 5.0
yourCircle.radius = 100;
yourCirclreference value
e
Assign object
reference to
yourCircle
33
Topic 1 Introduction
: Circle
radius: 1.0
SSK3101 Computer
Trace Code, cont.
Circle myCircle = new Circle(5.0);
Circle yourCircle = new Circle();
myCircl reference value
e
: Circle
yourCircle.radius = 100;
radius: 5.0
yourCirclreference value
e
: Circle
Change
radius in
yourCircle
34
Topic 1 Introduction
radius: 1.0
SSK3101 Computer
Reference Data Fields
The data fields can be of reference types. For
example, the following Student class contains a
data field name of the String type.
public class Student {
String name; // name has default value null
int age; // age has default value 0
boolean isScienceMajor; // isScienceMajor has default value false
char gender; // c has default value '\u0000'
}
35
Topic 1 Introduction
SSK3101 Computer
The null Value
If a data field of a reference type does
not reference any object, the data
field holds a special literal value, null.
36
Topic 1 Introduction
SSK3101 Computer
Default Value for a Data Field
The default value of a data field is null for a
reference type, 0 for a numeric type, false for a
boolean type, and '\u0000' for a char type.
However, Java assigns no default value to a local
variable
inside
a
method.
public class Test {
public static void main(String[] args) {
Student student = new Student();
System.out.println("name? " + student.name);
System.out.println("age? " + student.age);
System.out.println("isScienceMajor? " + student.isScienceMajor);
System.out.println("gender? " + student.gender);
}
}
37
Topic 1 Introduction
SSK3101 Computer
Example
Java assigns no default value to a local
variable inside a method.
public class Test {
public static void main(String[] args) {
int x; // x has no default value
String y; // y has no default value
System.out.println("x is " + x);
System.out.println("y is " + y);
}
}
Compilation error:
variables not initialized
38
Topic 1 Introduction
SSK3101 Computer
1. public class TestCircle1 {
2. public static void main(String[] args) {
3.
double localVar;
4.
//Circle1 myCircle = new Circle1(5.0);
5.
//System.out.println(“The area of the circle of radius “ +
6.
myCircle.radius + “ is “ +
7.
myCircle.getArea());
8.
Circle1 yourCircle = new Circle1();
9.
System.out.println(“The default value for radius is “ +
10.
yourCircle.radius);
11.
System.out.println(“Default value for local variable is “ +
12.
localVar);
13.
// yourCircle.radius = 100;
14.
//System.out.println(“The area of the circle of radius “ +
15.
yourCircle.radius + “ is “ +
16.
yourCircle.getArea());
17.
}
18. }
39
Differences between Variables of
Primitive Data Types and Object
Types
41
Topic 1 Introduction
SSK3101 Computer
Copying Variables of Primitive
Data Types and Object Types
42
Topic 1 Introduction
SSK3101 Computer
Garbage Collection
As shown in the previous figure, after the assignment
statement c1 = c2,
c1 points to the same object referenced by c2.
The object previously referenced by c1 is no longer
referenced.
This object is known as garbage.
Garbage is automatically collected by Java Virtual
Machine (JVM).
TIP:
If you know that an object is no longer needed, you
can explicitly assign null to a reference variable for
the object.
The JVM will automatically collect the space if the
43
object is not referenced by any variable.
Topic 1 Introduction
SSK3101 Computer
Garbage Collection, cont
If an object remains referenced but is no longer used in a program, the garbage collector does not
recycle the memory:
Square mySquare = new Square (5.0); // a 5.0 x 5.0 square
double areaSquare = mySquare.area();
Triangle myTriangle = new Triangle(6.0, 8.0); // right triangle base = 6.0, height = 8.0
double areaTriangle = myTriangle.area();
Circle myCircle = new Circle(4.0); // a circle of radius 4.0
double areaCircle = myCirclearea();
…
// code that uses these objects
…
// more code that does not use the objects created above
...
44
When Square, Triangle and Circle objects are no longer used by the program, if the objects remain
referenced, that is, if references mySquare, myTriangle, and myCircle continue to hold the addresses
of these obsolete objects, the garbage collector will not reclaim the memory for these three objects.
Such a scenario causes a memory leak.
Topic 1 Introduction
SSK3101 Computer
Garbage Collection, cont
A memory leak occurs when an application fails to release or recycle memory that is no longer
needed.
The memory leak caused by the Square-Triangle-Circle fragment can be easily rectified by adding a
few lines of code :
Square mySquare = new Square (5.0); // a 5.0 x 5.0 square
double areaSquare = mySquare.area();
Triangle myTriangle = new Triangle(6.0, 8.0); // right triangle base = 6.0, height = 8.0
double areaTriangle = myTriangle.area();
Circle myCircle = new Circle(4.0);
// a circle of radius 4.0
double areaCircle = myCircle.area()
// code that uses these objects
…
mySquare = null;
myTriangle = null;
myCircle = null;
// more code that does not use the objects created above
...
45
The Java constant null can be assigned to a reference.
A reference with value null refers to no object and holds no address; it is called a void reference.
Topic 1 Introduction
SSK3101 Computer
Garbage Collection, cont
Referenced and unreferenced objects
46
46
Topic 1 Introduction
SSK3101 Computer
Instance Variables, and Instance
Methods
Instance variables belong to a specific
instance.
Instance methods are invoked by an
instance of the class.
47
Topic 1 Introduction
SSK3101 Computer
Static Variables, Constants, and
Methods
Static variables are shared by all the
instances of the class.
Static methods are not tied to a specific
object.
Static constants are final variables shared
by all the instances of the class.
To declare static variables, constants, and
methods, use the static modifier.
48
Array of Objects
Circle[] circleArray = new Circle[10];
An array of objects is actually an array of reference
variables.
So invoking circleArray[1].getArea() involves two levels
of referencing as shown in the figure below.
circleArray references to the entire array.
circleArray[1] references to a Circle object.
51
Topic 1 Introduction
SSK3101 Computer
1. public class TotalArea {
2.
public static void main(String[] args) {
3.
Circle3[] circleArray;
4.
circleArray = createCircleArray();
5.
printCircleArray(circleArray);
6. }
7.
8. public static Circle3[] createCircleArray() {
9.
Circle3[] circleArray = new Circle3[10];
10.
for (int I = 0; I < circleArray.length; i++)
11.
circleArray[i] = new Circle3(Math.random() *
100);
12.
return circleArray;
13. }
52
Topic 1 Introduction
SSK3101 Computer
13. public static printCircleArray(Circle3[] circleArray) {
14.
System.out.println ("Radius\t\t\t\t" + "Area");
15.
for (int i = 0; i < circleArray.length; i++) {
16.
System.out.println(circleArray[i].getRadius() + "\t\t"
+
17.
circleArray[i].getArea() + ‘\n’);
18.
}
19.
System.out.println("-----------------");
20.
System.out.println("The total areas of circles is \t" +
21.
sum(circleArray);
22. }
23.
24. public static double sum(Circle3[] circleArray) {
25.
double sum = 0;
26.
for (int i = 0; i < circleArray.length; i++)
27.
sum += circleArray[i].getArea();
28.
return sum;
29. }
53
Topic 1 Introduction
SSK3101 Computer
1.6 Class Abstraction
and Encapsulation
55
Class Abstraction and
Encapsulation
Class abstraction means to separate class
implementation from the use of the class.
The creator of the class provides a description of the
class and let the user know how the class can be used.
The user of the class does not need to know how the
class is implemented.
The detail of implementation is encapsulated and
hidden from the user.
Topic 1 Introduction
SSK3101 Computer
Visibility Modifiers
By default, the class, variable, or method can
be
accessed
public by any class in the same package.
The class, data, or method is visible to any class in
any package.
private
The data or methods can be accessed only by the
declaring class.
The get and set methods are used to read and modify
private properties.
56
Topic 1 Introduction
SSK3101 Computer
package p1;
public class C1 {
public int x;
int y;
private int z;
package p2;
public class C2 {
void aMethod() {
C1 o = new C1();
can access o.x;
can access o.y;
cannot access o.z;
}
}
can invoke o.m1();
can invoke o.m2();
cannot invoke o.m3();
package p1;
class C1 {
...
}
57
public class C3 {
void aMethod() {
C1 o = new C1();
can access o.x;
cannot access o.y;
cannot access o.z;
}
}
can invoke o.m1();
cannot invoke o.m2();
cannot invoke o.m3();
package p2;
public class C2 {
can access C1
}
public class C3 {
cannot access C1;
can access C2;
}
The private modifier restricts access to within a class,
the default modifier restricts access to within a
package, and the public modifier enables unrestricted
access.
Topic 1 Introduction
SSK3101 Computer
NOTE
An object cannot access its private members, as shown
in (b). It is OK, however, if the object is declared in its
own class, as shown in (a).
58
Topic 1 Introduction
SSK3101 Computer
Why Data Fields Should Be private?
To protect data.
To make class easy to maintain.
59
Topic 1 Introduction
SSK3101 Computer
Why Data Fields Should Be private?
60
Example:
Data field radius and numberOfObjects in the Circle2
class can be modified directly (e.g. myCircle.radius =
5).
This is not a good practice:
Data may be tampered. For example,
numberOfObjects is to count the number of objects
created, but it may be set to an arbitrary value (e.g.
Circle2.numberOfObjects = 10).
It makes the class difficult to maintain and vulnerable
to bugs. Suppose you want to modify the Circle2 class
to ensure that the radius is non-negative after other
programs have already used the class. You have to
change not only the Circle2 class, but also the
programs that use the Circle2 class.
Topic 1 Introduction
SSK3101 Computer
Why Data Fields Should Be
private?
Data field encapsulation: declare the data field as
private to prevent direct modification of properties
Provide a get method to return the value of the data
field. (getter/accessor)
Provide a set method to enable a private data field to
be updated (setter/mutator)
61
Accessor method does not change the state of its implicit
parameter.
Mutator method changes the state
Topic 1 Introduction
SSK3101 Computer
Example of Data Field
Encapsulation
62
Topic 1 Introduction
SSK3101 Computer
1.
public class Circle3 {
2.
private double radius = 1;
3.
private static int numberOfObjects = 0;
4.
5.
public Circle3( ) {
6.
numberOfObjects++;
}
7.
8.
public Circle2(double newRadius) {
9.
radius = newRadius;
10.
numberOfObjects++;
}
11.
12.
public void setRadius(double newRadius ) {
13.
radius = (newRadius >= 0) ? newRadius : 0;
14.
15.
public static int getNumberOfObjects() {
16.
return numberOfObjects; }
17.
18.
public double getArea() {
19.
return radius * radius * Math.PI
20.
}
21. }
63
Topic 1 Introduction
}
SSK3101 Computer
Immutable Objects and Classes
• If the contents of an object cannot be changed once
the object is created, the object is called an
immutable object and its class is called an
immutable class.
• If you delete the set method in the Circle class in
the preceding example, the class would be
immutable because radius is private and cannot be
• A
class with
all private
fields and without
changed
without
a set data
method.
mutators is not necessarily immutable.
• For example, the following Student class has all
private data fields and no mutators, but it is
mutable.
64
Topic 1 Introduction
SSK3101 Computer
Example
public class Student {
private int id;
private BirthDate birthDate;
public class BirthDate {
private int year;
private int month;
private int day;
public BirthDate(int newYear,
int newMonth, int newDay) {
year = newYear;
month = newMonth;
day = newDay;
}
public Student(int ssn,
int year, int month, int day) {
id = ssn;
birthDate = new BirthDate(year, month, day);
}
public int getId() {
return id;
}
public BirthDate getBirthDate() {
return birthDate;
}
}
public void setYear(int newYear) {
year = newYear;
}
}
public class Test {
public static void main(String[] args) {
Student student = new Student(111223333, 1970, 5, 3);
BirthDate date = student.getBirthDate();
date.setYear(2010); // Now the student birth year is changed!
}
}
65
Topic 1 Introduction
SSK3101 Computer
What Class is Immutable?
For a class to be immutable, it must mark all data
fields private and provide no mutator methods and
no accessor methods that would return a reference
to a mutable data field object.
66
Topic 1 Introduction
SSK3101 Computer
1.8 Passing Objects to
Methods
Passing Objects to Methods
68
Passing by value for primitive type value (the value
is passed to the parameter)
Passing by value for reference type value (the value
is the reference to the object)
Topic 1 Introduction
SSK3101 Computer
Scope of Variables
69
The scope of instance and static variables is the
entire class. They can be declared anywhere
inside a class.
The scope of a local variable starts from its
declaration and continues to the end of the
block that contains the variable. A local variable
must be initialized explicitly before it can be
used.
The exception is when a data field is initialized
based on reference to another data field.
Topic 1 Introduction
SSK3101 Computer
Scope of Variables
public class Circle {
public double find getArea() {
return radius * radius * Math.PI;
}
public class Foo {
private i;
private int j = i + 1;
}
class Foo {
private double radius = 1;
int x = 0;
}
int y = 0;
Foo() {
}
void p() {
int x = 1;
System.out.println(“x = “ + x);
System.out.println(“y = “ + y);
}
}
70
Topic 1 Introduction
SSK3101 Computer
Example: The Loan Class
Loan
-annualInterestRate: double
The annual interest rate of the loan (default: 2.5).
Constructs a loan with specified interest rate, years, and
loan amount.
+getAnnualInterestRate(): double
Returns the annual interest rate of this loan.
+getNumberOfYears(): int
Returns the number of the years of this loan.
+getLoanAmount(): double
Returns the amount of this loan.
+getLoanDate(): Date
Returns the date of the creation of this loan.
+setAnnualInterestRate(
Sets a new annual interest rate to this loan.
annualInterestRate: double): void
Sets a new number of years to this loan.
+setNumberOfYears(
numberOfYears: int): void
71
Topic 1 Introduction
+setLoanAmount(
loanAmount: double): void
Sets a new amount to this loan.
+getMonthlyPayment(): double
Returns the monthly payment of this loan.
+getTotalPayment(): double
Returns the total payment of this loan.
SSK3101 Computer
Source code: The Loan Class
public class Loan {
private double annualInterestRate;
private int numberOfYears;
private double loanAmount;
private java.util.Date loanDate;
/** Default constructor */
public Loan() {
this(7.5, 30, 100000);
}
public Loan(double annualInterestRate, int numberOfYears,
double loanAmount) {
this.annualInterestRate = annualInterestRate;
this.numberOfYears = numberOfYears;
this.loanAmount = loanAmount;
loanDate = new java.util.Date();
}
72
Topic 1 Introduction
SSK3101 Computer
import javax.swing.JOptionPane;
public class TestLoanClass {
/** Main method */
public static void main(String[] args) {
// Enter yearly interest rate
String annualInterestRateString = JOptionPane.showInputDialog("Enter yearly interest rate, for example
8.25:");
double annualInterestRate = Double.parseDouble(annualInterestRateString); // Convert string to double
// Enter number of years
String numberOfYearsString = JOptionPane.showInputDialog("Enter number of years as an integer, \nfor
example 5:");
int numberOfYears = Integer.parseInt(numberOfYearsString); // Convert string to int
// Enter loan amount
String loanString = JOptionPane.showInputDialog("Enter loan amount, for example 120000.95:");
double loanAmount = Double.parseDouble(loanString); // Convert string to double
Loan loan = new Loan(annualInterestRate, numberOfYears, loanAmount); // Create Loan object
// Format to keep two digits after the decimal point
double monthlyPayment = (int)(loan.getMonthlyPayment() * 100) / 100.0;
double totalPayment = (int)(loan.getTotalPayment() * 100) / 100.0;
// Display results
String output = "The loan was created on " +loan.getLoanDate().toString() + "\nThe monthly payment is "
+
monthlyPayment + "\nThe total payment is " + totalPayment;
JOptionPane.showMessageDialog(null, output);
}
73
}
Topic 1 Introduction
SSK3101 Computer
Summary
OO Programming Concepts
Class Definition
75
The main thing you do to write class
definition for the various that will make up
the program.
A class definition encapsulates its object’s
data and behavior.
Once a class has been defined, it serves as a
template, or blueprint, for creating individual
objects or instance of the class.
A class definition contains two types of
elements: variable and methods.
Variable – to store the objects information
Method – to process the information
Topic 1 Introduction
SSK3101 Computer
OO Programming Concepts
To design an object you need to answer
five basic questions:
What role will the object perform in
the program?
What data of information will it need?
What actions will it take?
What interface will it present to other
objects?
What information will it hide from
other objects?
76
Topic 1 Introduction
SSK3101 Computer
OO Programming Concepts
77
Example, Problem Specification
Design a class that will represent a
riddle with a given question and
answer. The definition of this class
should make it possible to store
different riddles and to retrieve a
riddle's question and answer
independently.
Choosing a program’s object is often a
matter of looking for noun in the
problem specification.
Topic 1 Introduction
SSK3101 Computer
OO Programming Concepts
Design specification for the Riddle class:
Class Name: Riddle
What role will the object perform in the program?
Role: To store and retrieve a question
and answer
What data of information will it need?
Information (attributes):
question: A variable to store a
riddle’s
question (private)
answer: A variable to store a riddle’s
answer (private)
78
Topic 1 Introduction
SSK3101 Computer
OO Programming Concepts
What actions will it take? (Looking for
verbs)
Actions (Behaviours)
Riddle(): A method to set a
riddle’s
question and answer
getQuestion: A method to return
a
riddle’s question
getAnswer(): A method to return
a
riddle’s answer
A method is a named section of code
79
Topic 1 Introduction
SSK3101 Computer
OO Programming Concepts
What interface will it present to other
objects?
An object’s interface should consist of
just those methods needed to
communicate with or to use the
object
What information will it hide from other
objects?
An object should hide most of the
details of its implementation
80