java object oriented programming

Post on 17-Jul-2016

48 Views

Category:

Documents

2 Downloads

Preview:

Click to see full reader

DESCRIPTION

Introduction to java object oriented programming

TRANSCRIPT

SSK 3101 COMPUTER PROGRAMMING IITopic 1 Introduction

Dr. Nor Fazlida Mohd SaniDepartment of Computer Science

Faculty of Computer Science and Information TechnologyUniversity Putra of Malaysia

Room No: C2.04

2 Topic 1 Introduction SSK3101 Computer Programming II

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)

3 Topic 1 Introduction SSK3101 Computer Programming II

Chapter 1 Outline 1. Introduction

This chapter will cover the following topics:

1.1 Object-oriented Programming ConceptsObjectsClasses

1.2 Constructors1.3 Constructing Objects Using Constructors1.4 Accessing Objects via Reference Variables1.5 Array of Objects1.6 Class Abstraction and Encapsulation1.7 Visibility Modifiers1.8 Passing Objects to Methods

1.1 Object-oriented Programming Concepts

5 Topic 1 Introduction SSK3101 Computer Programming II

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. A set of methods that use or manipulate the data (the

behaviors).

6 Topic 1 Introduction SSK3101 Computer Programming II

Objects – Example 1.1

An object has both a state and behavior. The state defines the object, and the behavior defines what the object does.

Class Name: CircleData Fields: radius is ______Methods: getArea()

Circle Object 1Data Fields: radius is 10

Circle Object 2Data Fields: radius is 25

Circle Object 3Data Fields: radius is 125

A class templates

Three objects of class Circle

7 Topic 1 Introduction SSK3101 Computer Programming II

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.

8 Topic 1 Introduction SSK3101 Computer Programming II

Objects – Example 1.2 (Cont.)Three different remote objects, each with a unique attribute values (data) but all sharing the same methods or behaviors.

9 Topic 1 Introduction SSK3101 Computer Programming II

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.

10 Topic 1 Introduction SSK3101 Computer Programming II

Objects – Example 1.3 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

11 Topic 1 Introduction SSK3101 Computer Programming II

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.

12 Topic 1 Introduction SSK3101 Computer Programming II

Unified Modelling Language (UML) Class Diagram

Circle

radius : double

Circle()Circle(newRadius : double)getArea() double

circle1 : Circle radius : 10

circle2 : Circle radius : 25

circle3 : Circle radius : 125

UML notation for objects

Data fields

Constructors andMethods

Class name

13 Topic 1 Introduction SSK3101 Computer Programming II

Classesclass Circle {

/** The radius of this circle */double radius = 1.0;

/** 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;}

}

Data field

Constructors

Method

14 Topic 1 Introduction SSK3101 Computer Programming II

Classes – Exercise 1Rectangle 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

1.2 Constructors

16 Topic 1 Introduction SSK3101 Computer Programming II

Constructors

• Example:Circle() {}

Circle(double newRadius) { radius = newRadius;}

• Constructors are a special kind of methods that are invoked to construct a new object, initialize it with the construction parameters, and return a reference to the constructed object.

17 Topic 1 Introduction SSK3101 Computer Programming II

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.

18 Topic 1 Introduction SSK3101 Computer Programming II

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.

1.3 Constructing Objects Using Constructors

20 Topic 1 Introduction SSK3101 Computer Programming II

Creating Objects Using Constructors

Syntax:new ClassName(); // default constructornew ClassName(parameter);

Example:new Circle();new Circle(5.0);

21 Topic 1 Introduction SSK3101 Computer Programming II

Declaring Object Reference VariablesTo reference an object, assign the object to a reference variable.

To declare a reference variable, use the syntax:ClassName objectRefVar;

Example:Circle myCircle;

22 Topic 1 Introduction SSK3101 Computer Programming II

Declaring/Creating Objects in a Single Step

ClassName objectRefVar = new ClassName();Example:

Circle myCircle = new Circle();

Create an objectAssign object reference

1.4 Accessing Objects via Reference Variables

24 Topic 1 Introduction SSK3101 Computer Programming II

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

25 Topic 1 Introduction SSK3101 Computer Programming II

A Simple Circle Class

Objective: Demonstrate creating objects, accessing data, and using methods.

26 Topic 1 Introduction SSK3101 Computer Programming II

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()); 11. yourCircle.radius = 100;12. System.out.println("The area of the

circle of radius " + 13.

yourCircle.radius + " is " + 14.

yourCircle.getArea());15. }16. }

27 Topic 1 Introduction SSK3101 Computer Programming II

17.class Circle {18. double radius;19. Circle( ) {20. radius = 1.0;21. }22. Circle(double newRadius) {23. radius = newRadius;24. }25. double getArea( ) {26. return radius * radius *

radius * Math.PI;27. }28.}

28 Topic 1 Introduction SSK3101 Computer Programming II

Trace Code

Circle myCircle = new Circle(5.0);

Circle yourCircle = new Circle();

yourCircle.radius = 100;

Declare myCircle

no valuemyCircle

29 Topic 1 Introduction SSK3101 Computer Programming II

Trace Code, cont.

Circle myCircle = new Circle(5.0);

Circle yourCircle = new Circle();

yourCircle.radius = 100;

no valuemyCircle

Create a Circle

: Circleradius: 5.0

30 Topic 1 Introduction SSK3101 Computer Programming II

Trace Code, cont.

Circle myCircle = new Circle(5.0);

Circle yourCircle = new Circle();

yourCircle.radius = 100;

reference valuemyCircle

Assign object reference to

myCircle

: Circleradius: 5.0

31 Topic 1 Introduction SSK3101 Computer Programming II

Trace Code, cont.reference valuemyCircl

e

no valueyourCircle

Declare yourCircle

Circle myCircle = new Circle(5.0);

Circle yourCircle = new Circle();

yourCircle.radius = 100;

: Circleradius: 5.0

32 Topic 1 Introduction SSK3101 Computer Programming II

Trace Code, cont.reference valuemyCircl

e

no valueyourCircle

Circle myCircle = new Circle(5.0);

Circle yourCircle = new Circle();

yourCircle.radius = 100;

Create a new Circle

object

: Circleradius: 0.0

: Circleradius: 5.0

33 Topic 1 Introduction SSK3101 Computer Programming II

Circle myCircle = new Circle(5.0);

Circle yourCircle = new Circle();

yourCircle.radius = 100;

Trace Code, cont.reference valuemyCircl

e

reference valueyourCircle

Assign object reference to yourCircle

: Circleradius: 5.0

: Circleradius: 1.0

34 Topic 1 Introduction SSK3101 Computer Programming II

Trace Code, cont.Circle myCircle = new Circle(5.0);

Circle yourCircle = new Circle();

yourCircle.radius = 100;

reference valuemyCircle

reference valueyourCircle

Change radius in

yourCircle

: Circleradius: 5.0

: Circleradius: 1.0

35 Topic 1 Introduction SSK3101 Computer Programming II

Reference Data FieldsThe 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'}

36 Topic 1 Introduction SSK3101 Computer Programming II

The null ValueIf a data field of a reference type does not reference any object, the data field holds a special literal value, null.

37 Topic 1 Introduction SSK3101 Computer Programming II

Default Value for a Data FieldThe 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); }}

38 Topic 1 Introduction SSK3101 Computer Programming II

Example

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

Java assigns no default value to a local variable inside a method.

39 Topic 1 Introduction SSK3101 Computer Programming II

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

40 Topic 1 Introduction SSK3101 Computer Programming II

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

41 Topic 1 Introduction SSK3101 Computer Programming II

Differences between Variables of Primitive Data Types and Object

Types

42 Topic 1 Introduction SSK3101 Computer Programming II

Copying Variables of Primitive Data Types and Object Types

43 Topic 1 Introduction SSK3101 Computer Programming II

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 object is not referenced by any variable.

44 Topic 1 Introduction SSK3101 Computer Programming II

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 squaredouble areaSquare = mySquare.area();

Triangle myTriangle = new Triangle(6.0, 8.0); // right triangle base = 6.0, height = 8.0double areaTriangle = myTriangle.area();

Circle myCircle = new Circle(4.0); // a circle of radius 4.0double areaCircle = myCirclearea();…// code that uses these objects…// more code that does not use the objects created above

...

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.

45 Topic 1 Introduction SSK3101 Computer Programming II

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 squaredouble areaSquare = mySquare.area(); Triangle myTriangle = new Triangle(6.0, 8.0); // right triangle base = 6.0, height = 8.0double areaTriangle = myTriangle.area();

Circle myCircle = new Circle(4.0); // a circle of radius 4.0double areaCircle = myCircle.area() // code that uses these objects…mySquare = null; myTriangle = null;myCircle = null; // more code that does not use the objects created above

... 

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.

46 Topic 1 Introduction SSK3101 Computer Programming II

46

Garbage Collection, cont

Referenced and unreferenced objects

47 Topic 1 Introduction SSK3101 Computer Programming II

Instance Variables, and Instance Methods

Instance variables belong to a specific instance.

Instance methods are invoked by an instance of the class.

48 Topic 1 Introduction SSK3101 Computer Programming II

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.

49 Topic 1 Introduction SSK3101 Computer Programming II

1. class Circle2 {2. double radius;3. static int numberOfObjects = 0;4. 5. Circle2( ) {6. radius = 1.07. 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. }

1.5 Array of Objects

51 Topic 1 Introduction SSK3101 Computer Programming II

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.

52 Topic 1 Introduction SSK3101 Computer Programming II

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

53 Topic 1 Introduction SSK3101 Computer Programming II

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

1.6 Class Abstraction and Encapsulation

55 Topic 1 Introduction SSK3101 Computer Programming II

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.

56 Topic 1 Introduction SSK3101 Computer Programming II

Visibility ModifiersBy default, the class, variable, or method can beaccessed by any class in the same package. public

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.

57 Topic 1 Introduction SSK3101 Computer Programming II

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.

public class C1 { public int x; int y; private int z; public void m1() { } void m2() { } private void m3() { } }

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; package p2;

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(); } }

class C1 { ... }

public class C2 { can access C1 }

package p1; package p2; public class C3 { cannot access C1; can access C2; }

58 Topic 1 Introduction SSK3101 Computer Programming II

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

59 Topic 1 Introduction SSK3101 Computer Programming II

Why Data Fields Should Be private?

To protect data.To make class easy to maintain.

60 Topic 1 Introduction SSK3101 Computer Programming II

Why Data Fields Should Be private? 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.

61 Topic 1 Introduction SSK3101 Computer Programming II

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) Accessor method does not change the state of its implicit

parameter. Provide a set method to enable a private data field to

be updated (setter/mutator) Mutator method changes the state

62 Topic 1 Introduction SSK3101 Computer Programming II

Example of Data Field Encapsulation

63 Topic 1 Introduction SSK3101 Computer Programming II

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.PI20. }21. }

64 Topic 1 Introduction SSK3101 Computer Programming II

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 changed without a set method. • A class with all private data fields and without mutators is not necessarily immutable.

• For example, the following Student class has all private data fields and no mutators, but it is mutable.

65 Topic 1 Introduction SSK3101 Computer Programming II

Examplepublic class Student { private int id; private BirthDate birthDate;

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 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 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! }}

66 Topic 1 Introduction SSK3101 Computer Programming II

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.

1.8 Passing Objects to Methods

68 Topic 1 Introduction SSK3101 Computer Programming II

Passing Objects to Methods 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)

69 Topic 1 Introduction SSK3101 Computer Programming II

Scope of Variables 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.

70 Topic 1 Introduction SSK3101 Computer Programming II

Scope of Variablespublic class Circle { public double find getArea() { return radius * radius * Math.PI; }

private double radius = 1;}

public class Foo { private i; private int j = i + 1;}

class Foo { int x = 0; int y = 0;

Foo() { }

void p() { int x = 1; System.out.println(“x = “ + x); System.out.println(“y = “ + y); }}

71 Topic 1 Introduction SSK3101 Computer Programming II

Example: The Loan Class

Loan

-annualInterestRate: double -numberOfYears: int -loanAmount: double -loanDate: Date +Loan() +Loan(annualInterestRate: double,

numberOfYears: int, loanAmount: double)

+getAnnualInterestRate(): double +getNumberOfYears(): int +getLoanAmount(): double +getLoanDate(): Date +setAnnualInterestRate( annualInterestRate: double): void +setNumberOfYears( numberOfYears: int): void +setLoanAmount( loanAmount: double): void +getMonthlyPayment(): double +getTotalPayment(): double

The annual interest rate of the loan (default: 2.5). The number of years for the loan (default: 1) The loan amount (default: 1000). The date this loan was created. Constructs a default Loan object. Constructs a loan with specified interest rate, years, and

loan amount. Returns the annual interest rate of this loan. Returns the number of the years of this loan. Returns the amount of this loan. Returns the date of the creation of this loan. Sets a new annual interest rate to this loan.

Sets a new number of years to this loan. Sets a new amount to this loan. Returns the monthly payment of this loan. Returns the total payment of this loan.

72 Topic 1 Introduction SSK3101 Computer Programming II

Source code: The Loan Classpublic 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(); }

73 Topic 1 Introduction SSK3101 Computer Programming II

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); }}

Summary

75 Topic 1 Introduction SSK3101 Computer Programming II

OO Programming ConceptsClass Definition

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

76 Topic 1 Introduction SSK3101 Computer Programming II

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?

77 Topic 1 Introduction SSK3101 Computer Programming II

OO Programming Concepts 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.

78 Topic 1 Introduction SSK3101 Computer Programming II

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)

79 Topic 1 Introduction SSK3101 Computer Programming II

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

that can be invoked, or called upon, to perform a particular action.

80 Topic 1 Introduction SSK3101 Computer Programming II

80

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

End of Chapter 1

top related