Java Object Oriented Programming
Java Object Oriented Programming
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
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)
Topic 1 Introduction
SSK3101 Computer
Chapter 1 Outline
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
Topic 1 Introduction
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
Topic 1 Introduction
SSK3101 Computer
SSK3101 Computer
Topic 1 Introduction
SSK3101 Computer
Topic 1 Introduction
SSK3101 Computer
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.
11
Topic 1 Introduction
SSK3101 Computer
UML notation
for objects
12
Circle
Class name
radius : double
Data fields
Circle()
Circle(newRadius :
double)
getArea() double
circle1 : Circle
circle2 : Circle
radius : 10
radius : 25
Topic 1 Introduction
Constructors and
Methods
circle3 : Circle
radius : 125
SSK3101 Computer
Classes
classCircle{
/**Theradiusofthiscircle*/
doubleradius=1.0;
Data field
/**Constructacircleobject*/
Circle(){
}
/**Constructacircleobject*/
Circle(doublenewRadius){
radius=newRadius;
}
/**Returntheareaofthiscircle*/
doublegetArea(){
returnradius*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,
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
20
Topic 1 Introduction
SSK3101 Computer
21
Topic 1 Introduction
SSK3101 Computer
Example:
Assign object
reference
Create an object
22
Topic 1 Introduction
SSK3101 Computer
Accessing Objects
e.g., myCircle.radius
e.g., myCircle.getArea()
24
Topic 1 Introduction
SSK3101 Computer
25
Objective:
Demonstrate creating objects,
accessing data, and using
methods.
Topic 1 Introduction
SSK3101 Computer
1.publicclassTestCircle1{
2. publicstaticvoidmain(String[]args){
3. CirclemyCircle=newCircle(5.0);
4. System.out.println("Theareaofthe
circleofradius"+
5.
myCircle.radius+"is"+
6.
myCircle.getArea());
7. CircleyourCircle=newCircle();
8. System.out.println("Theareaofthe
circleofradius"+
9.
yourCircle.radius+"is"+
10.
yourCircle.getArea());
26
Topic 1 Introduction
SSK3101 Computer
27
17.classCircle{
18.doubleradius;
19.Circle(){
20.radius=1.0;
21.}
22.Circle(doublenewRadius){
23.radius=newRadius;
24.}
25.doublegetArea(){
26.returnradius*radius*
radius*Math.PI;
27.}
28.}
Topic 1 Introduction
SSK3101 Computer
Trace Code
Declare myCircle
myCircl
e
no value
yourCircle.radius = 100;
28
Topic 1 Introduction
SSK3101 Computer
myCircl
e
no value
: Circle
yourCircle.radius = 100;
radius: 5.0
Create a
Circle
29
Topic 1 Introduction
SSK3101 Computer
yourCircle.radius = 100;
: Circle
Assign object
reference to
myCircle
30
Topic 1 Introduction
radius: 5.0
SSK3101 Computer
: Circle
radius: 5.0
yourCircle.radius = 100;
yourCircl
e
no value
Declare
yourCircle
31
Topic 1 Introduction
SSK3101 Computer
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
: 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
yourCircle.radius = 100;
radius: 5.0
yourCirclreference value
e
: Circle
Change
radius in
yourCircle
34
Topic 1 Introduction
radius: 1.0
SSK3101 Computer
35
Topic 1 Introduction
SSK3101 Computer
36
Topic 1 Introduction
SSK3101 Computer
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
Topic 1 Introduction
SSK3101 Computer
Topic 1 Introduction
SSK3101 Computer
41
Topic 1 Introduction
SSK3101 Computer
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.
SSK3101 Computer
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();
// 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.
SSK3101 Computer
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()
mySquare = null;
myTriangle = null;
myCircle = null;
// more code that does not use the objects created above
...
45
SSK3101 Computer
46
46
Topic 1 Introduction
SSK3101 Computer
47
Topic 1 Introduction
SSK3101 Computer
Topic 1 Introduction
SSK3101 Computer
1. class Circle2 {
2.
double radius;
3.
static int numberOfObjects = 0;
4.
5.
Circle2( ) {
6.
radius = 1.0
7.
numberOfObjects++;
}
8.
9.
Circle2(double newRadius) {
10.
radius = newRadius;
11.
numberOfObjects++;
}
12.
13.
double getArea( ) {
14.
return radius * radius * Math.PI;
}
15.
16.
static int getNumberOfObjects() {
17.
return numberOfObjects; }
18. }
49
Topic 1 Introduction
SSK3101 Computer
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
Topic 1 Introduction
SSK3101 Computer
Topic 1 Introduction
SSK3101 Computer
and Encapsulation
55
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.
private
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;
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;
package p2;
public class C2 {
can access C1
}
public class C3 {
cannot access C1;
can access C2;
}
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
59
Topic 1 Introduction
SSK3101 Computer
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
61
Topic 1 Introduction
SSK3101 Computer
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
64
Topic 1 Introduction
SSK3101 Computer
Example
public class Student {
private int id;
private BirthDate birthDate;
Topic 1 Introduction
SSK3101 Computer
66
Topic 1 Introduction
SSK3101 Computer
Methods
68
Topic 1 Introduction
SSK3101 Computer
Scope of Variables
69
Topic 1 Introduction
SSK3101 Computer
Scope of Variables
public class Circle {
public double find getArea() {
return radius * radius * Math.PI;
}
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
-numberOfYears: int
-loanAmount: double
-loanDate: Date
+Loan()
+Loan(annualInterestRate: double,
numberOfYears: int,
loanAmount: double)
+getAnnualInterestRate(): double
+getNumberOfYears(): int
+getLoanAmount(): double
+getLoanDate(): Date
+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
+getMonthlyPayment(): double
+getTotalPayment(): double
SSK3101 Computer
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
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
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
riddles
question (private)
answer: A variable to store a riddles
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
riddles
question and answer
getQuestion: A method to return
a
riddles question
getAnswer(): A method to return
a
riddles 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 objects 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
80
Topic 1 Introduction
SSK3101 Computer
End of Chapter 1