Você está na página 1de 81

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)

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

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

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.

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.

11

Topic 1 Introduction

SSK3101 Computer

Unified Modelling Language (UML)


Class Diagram

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,

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 objects data:


objectRefVar.data

e.g., myCircle.radius

Invoking the objects 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.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

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

Topic 1 Introduction

SSK3101 Computer

17. class Circle1 {


18.
double radius;
19.
Circle1( ) {
20. //
radius = 1.0;
21.
}
22.
Circle1(double newRadius) {
23.
radius = newRadius;
24.
}
25.
double getArea( ) {
26.
return radius * radius * radius *
27.
Math.PI;
28.
}
29. }
40

Topic 1 Introduction

SSK3101 Computer

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

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

1.5 Array of Objects

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;

public void m1() {


}
void m2() {
}
private void m3() {
}

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).

-numberOfYears: int

The number of years for the loan (default: 1)

-loanAmount: double

The loan amount (default: 1000).

-loanDate: Date

The date this loan was created.

+Loan()

Constructs a default Loan object.

+Loan(annualInterestRate: double,
numberOfYears: int,
loanAmount: double)

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 objects
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 programs 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
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

Você também pode gostar