computer programming 11/12 - weebly€¦ · object-oriented programming •the object-oriented...

67
Computer Programming 11/12 Unit 5 Classes, Objects, and Methods

Upload: others

Post on 10-Aug-2020

10 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

Computer Programming11/12

Unit 5 – Classes, Objects, and Methods

Page 2: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

1. Object-oriented programming• The object-oriented programming (OOP) has become a dominant

programming paradigm nowadays, and Java is one of the programming languages based on this philosophy.

• Comparison between traditional procedural programming (or procedure-oriented programming, POP) and OOP:

Procedural programming (POP) Object-oriented programming (OOP)

Emphasizes on algorithm Emphasizes on data

Program divided into functions Program divided into objects

Global data shared by all functions Data encapsulation

Top-down approach Bottom-up approach

Unit 5 - Classes, Objects and Methods 2

Page 3: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• Example: Running a simple web browser using POP vs. OOP

Unit 5 - Classes, Objects and Methods 3

Page 4: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• Java programs consist of classes, objects, and methods that interact with one another. It is important to have a general idea about what they are and what they do.

1. Class

• A template or blueprint from which objects are made

• Specifies the attributes the objects in the class have

2. Object

• The items to be produced based on the class

• Known as instances

3. Method

• The actual way how an object is made (or how it works) based on the class

Unit 5 - Classes, Objects and Methods 4

Page 5: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• Example: A blueprint for building houses

Unit 5 - Classes, Objects and Methods 5

Page 6: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• The idea of class, object and method can be illustrated by considering the statement used to read in keyboard input.

Unit 5 - Classes, Objects and Methods 6

Scanner keyboard = new Scanner(System.in);

System.out.println(“Enter a number.”);

int x = keyboard.nextInt();

Creates an object called keyboard of the type Scanner. Here Scanner is a class.

System.in calls a constructor in Scanner class to create the object keyboard. The keyword new is needed when an object is created.

nextInt() is a method in Scanner class that returns an integer the user enters.

System.in tells the Scanner to read information from the keyboard.

Page 7: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

2. Methods

A. Introduction

• A method in Java is a sequence of declarations and executablestatements enclosed together like an independent mini program that performs a specific task.

• Methods are commonly used to break a big problems into smaller and more manageable ones; each of these pieces is then dealt with by several small methods. This approach is known as divide-and-conquer.

• A method written for a specific task can be used in many different places in a program where the same task is performed. This strategy is known as code reuse, a common feature observed in programming or engineering.

Unit 5 - Classes, Objects and Methods 7

Page 8: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• The most common method used in Java is the main() method which is used in every Java program.

• The main() method in Java takes the following form:

Unit 5 - Classes, Objects and Methods 8

public static void main(String[] args) {

statements …

}

Modifier: public means the method is available for code outside the class; static means this method belongs to the classbut not a specific object

Return-type: void means that the code executes but does not return a value

Method name: the name of the method (e.g. main)

Parentheses: variable declaration; the parameters required by the method are listed here

Block: the sequence of executable statements

Page 9: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• There are two general categories of methods in Java:

1. Void method

• This is a method that just performs a task and then terminates.

• For example:

• This code initializes a variable number and assigns a value of 7 to it. Then, this value is displayed on the screen, and the code stops.

Unit 5 - Classes, Objects and Methods 9

Task

Page 10: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

2. Value-returning method

• This method not only performs a task but also sends a value back to the code that called it.

• For example: nextInt() method in the Random class

• This code executes the nextInt() method within the Random class to produce a random integer, and assigns it to the variable number.

Unit 5 - Classes, Objects and Methods 10

Return a value

Page 11: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

B. Defining a method

• A definition is required in order to create a method. The definition of a method consists of two general parts:

1. Header

• At the beginning of a method

• Includes important things such as modifier, return type, and method name

2. Body

• Made of executable statements to be performed

• Included inside a pair of curly braces

Unit 5 - Classes, Objects and Methods 11

Page 12: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• For example:

Unit 5 - Classes, Objects and Methods 12

Method header:Not terminated by ;

Method body

Modifiers Return-type

Method’s name:e.g. displayMessage in this example

Page 13: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

C. Calling a method

• A method in a program is executed by a method call statement.

• When a method is called, the JVM branches to that method and executes the statements in its body.

• A simple method call statement looks like the following (referring to the example on previous slide):

• The statement is simply the name of the method followed by a set of parentheses. Arguments are included within the parentheses if required.

Unit 5 - Classes, Objects and Methods 13

displayMessage();

Page 14: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• For example:

Unit 5 - Classes, Objects and Methods 14

class SimpleMethod {public static void main(String[] args) {

System.out.println(“Hello from the main method.”);

displayMessage();

System.out.println(“Back in the main method.”);}

public static void displayMessage() {System.out.println(“Hello from the displayMessage method.”);

}

}

Page 15: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• Example: A program that calculates the cube of a given integer.

Unit 5 - Classes, Objects and Methods 15

class TestCube {public static void main(String[] args) {

for (int i = 0; i < 6; i++) System.out.println(i + “\t” + cube(i));

}

static void cube(int n) {return n*n*n

}}

• Calls the method cube() to compute the cube of a given integer i which is running from 0 to 5

• The integer i is passed to the method for calculation

• It returns the answer to the main method and is assigned to cube(i)

• This method is restricted to this TestCubeprogram only since no public keyword is used.

Page 16: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• When this program is executed, the following output is produced:

• Certainly, the same output can be produced if the cube calculation is programmed directly within the main method:

Unit 5 - Classes, Objects and Methods 16

0 01 12 83 274 645 125

for (i = 0; i < 6; i++) {n = i*i*i;System.out.println(i + “\t” + n);

}

Page 17: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• Example: A program that returns the minimum of its two integer arguments.

Unit 5 - Classes, Objects and Methods 17

import java.util.Random;class TestMin {

public static void main(String[] args) {Random random = new Random();for (int j = 0; j < 5; j++) {

int m = random.nextInt(100);int n = random.nextInt(100);int a = min(m, n);System.out.println(“min(” + m + “, ” + n + “) = ” + a);

}}static int min(int x, int y) {

if (x < y) return x;else return y;

}}

Page 18: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• This program creates two random numbers and determines which one is smaller. For example:

• Random numbers can be generated in Java by the Random() class. It is loaded using the following header:

• The random method is invoked as follows:

Unit 5 - Classes, Objects and Methods 18

min(16, 18) = 16min(83, 30) = 30min(68, 96) = 68min(17, 73) = 17

import java.util.Random;

Random name = new Random();int x = name.nextInt();

Page 19: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• Note that in this program, many variables are declared. For example: random, j, m, n, a, x, y.

• These variables are called local variables because they are used only within the method in which they are declared.

• Therefore,

• Local variables cease to exist when the method returns.

• An advantage of local variables is that same name can be used for different variables in the same program as long as they are local to different methods.

Unit 5 - Classes, Objects and Methods 19

Method Local variables

main() random, j, m, n

min() x, y

Page 20: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

D. Hierarchical method calls

• Methods can be called in a hierarchical, or layered fashion.

• For example, method A can call method B, which can then call method C. When method C finishes, the JVM returns to method B. When method B finishes, the JVM returns to method A.

Unit 5 - Classes, Objects and Methods 20

Method A Method B Method C

Page 21: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• The following example demonstrates the idea of hierarchical method calling:

Unit 5 - Classes, Objects and Methods 21

class DeepAndDeeper {public static void main(String[] args) {

System.out.println(“I am starting in main.”);deep();System.out.println(“Now I am back in main.”);

}

public static void deep() {System.out.println(“I am now in deep.”);deeper();System.out.println(“Now I am back in deep.”);

}

public static void deeper() {System.out.println(“I am now in deeper.”);

}

}

Page 22: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• When the program is executed, the following output is produced:

• Usually each method in a program is complemented with a commentthat provides a brief explanation of the method’s purpose.

• This is for the sake of the programmer who maintains the program.Unit 5 - Classes, Objects and Methods 22

I am starting in main.I am now in deep.I am now in deeper.Now I am back in deep.Now I am back in main.

/**comments

*/

Page 23: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• Example: Permutation is a useful concept in counting and probability that allows to determine the number of ways of arranging objects in order.

• Mathematically, permutation can be computed using the following equation:

• Equivalently, it can be expressed in terms of factorials:

Unit 5 - Classes, Objects and Methods 23

𝑃 𝑛, 𝑘 = 𝑛 𝑛 − 1 𝑛 − 2 ⋯ 𝑛 + 2 − 𝑘 𝑛 + 1 − 𝑘

𝑃 𝑛, 𝑘 =𝑛 𝑛 − 1 𝑛 − 2 ⋯ 3 2 1

𝑛 − 𝑘 𝑛 − 𝑘 − 1 ⋯ 3 2 1=

𝑛!

𝑛 − 𝑘 !

Page 24: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• A sample program that calculates permutation

Unit 5 - Classes, Objects and Methods 24

class TestPermutation {public static void main(String[] args) {

for (int i = 0; i < 9; i++) {for (int j = 0; j <= i; j++) {

System.out.print(p(i, j) + “\t”);System.out.println();

}}

static long p(int n, int k) {return f(n)/f(n-k);

}static long f(int n) {

long f = 1;while (n > 1)

f *= n--;return f;

}}

Page 25: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

E. Recursive method calling

• A method can invoke itself when being executed, and this process is called recursion.

• For example, we have seen that factorial is defined explicitly as

• In fact, factorial can also be defined recursively as

Unit 5 - Classes, Objects and Methods 25

𝑛! = ቊ1, 𝑛 < 2

𝑛 𝑛 − 1 !, 𝑛 ≥ 2

𝑛! = 𝑛 𝑛 − 1 𝑛 − 2 ⋯ 3 2 1

Page 26: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• The latter expression can be implemented efficiently using recursion:

Unit 5 - Classes, Objects and Methods 26

class TestFactorial {public static void main(String[] args) {

for (int i = 0; i < 9; i++) System.out.println(“f(” + i + “) = ” + f(i));

}static long f(int n) {

if (n < 2) return 1;else return n*f(n-1);

}} When f(i) is invoked, the value in

the preceding run is used to compute the new value. (i.e., recursion)

Page 27: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• When the program is run, the following output is produced:

Unit 5 - Classes, Objects and Methods 27

f(0) = 1f(1) = 1f(2) = 2f(3) = 6f(4) = 24f(5) = 120f(6) = 720f(7) = 5040f(8) = 40320

Page 28: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

3. ClassesA. Idea of blueprint

• A simple diagram for car:

Unit 5 - Classes, Objects and Methods 28

Page 29: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• With Java, as an object-oriented programming language, we create programs which are made of objects that control the actions of the program.

• But objects do not appear on their own and work themselves. Before they can be used, they have to be created in memory. And, before an object can be created in memory, a class for the object has to be defined.

• A class is the code that describes a particular type of object; it specifies the data that an object can hold and the actions that an object can perform.

• In other words, a class is a blueprint, and an object is an item, called instance, produced based on the blueprint.

Unit 5 - Classes, Objects and Methods 29

Page 30: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• Example: A blueprint (called Automobile) that defines automobiles

Unit 5 - Classes, Objects and Methods 30

Page 31: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• Using this class, we can create many instances such as follows:

Unit 5 - Classes, Objects and Methods 31

Page 32: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

B. API classes in Java

• We have seen and utilized some classes in the Java API already. For example:

Unit 5 - Classes, Objects and Methods 32

Class Method Usage

java.util.Scanner Scanner Read input from keyboard

java.util.Random Random Create a random number

java.io.* PrintWriter Write output to a file

javax.swing.JOptionPane showInputDialog Display content in a dialog box

Page 33: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• The most trivial class that we use in Java programming is the main class that contains the main() method. It is essentially the program itself.

• The main class has the specific form:

• Note that a class is a data type like other primitive types (e.g. int); however, it can invoke methods. For example:

Unit 5 - Classes, Objects and Methods 33

public static void main(String[] args) {

// program statements go here

}

Random r = new Random(100);

Page 34: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• A class has three kinds of members:

1. Fields

• Specify the kind of data that the objects hold

2. Methods

• Specify the operations that the objects can perform

3. Constructors

• Specify how the objects are to be created

Unit 5 - Classes, Objects and Methods 34

Page 35: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• Example: A Point class that abstracts a point in the Cartesian plane.

Unit 5 - Classes, Objects and Methods 35

public class Point {private int x, y;public Point(int x, int y) {

this.x = x;this.y = y;

}public boolean equals(Point p) {

return (x == p.x && y == p.y);}public int getX() {

return x;}public int getY() {

return y;}public String toString() {

return new String(“(” + x + “, ” + y + “)”);}

}

Two fields, x and y

constructor

Four methods

Page 36: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• This class cannot be executed directly because it does not contain the main() method. Hence, we need a separate test class that has the main() method:

Unit 5 - Classes, Objects and Methods 36

public class TestPoint {public static void main(String[] args) {

Point p = new Point(2, -3);System.out.println(“p: ” + p);System.out.println(“p.getX(): ” + p.getX());System.out.println(“p.getY(): ” + p.getY());Point q = new Point(7, 4);System.out.println(“q:” + q);System.out.println(“q.equals(p): ” + q.equals(p));System.out.println(“q.equals(q): ” + q.equals(q));

}}

Create an object p in the class Point

Invoke the methods getX() and getY()

Invoke the method equals()

Page 37: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• When this program is executed, the following output is produced:

Unit 5 - Classes, Objects and Methods 37

p: (2, -3)p.getX(): 2p.getY(): -3q: (7, 4)q.equals(p): falseq.equals(q): true

Page 38: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

C. Procedures of creating a class

• The Java API provides many prewritten classes that we can use to design our programs. However, sometimes we may need to accomplish a task that no existing class or method can handle. In that case, we will have to write our own class.

• To design a class, we employ a UML diagram (Universal Modeling Language) whose general layout is as follows:

Unit 5 - Classes, Objects and Methods 38

Page 39: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• Imagine that we are to create a class whose objects store information about rectangles.

• There are two required fields:

• length: the field that holds the rectangle’s length

• width: the field that holds the rectangle’s width

• There are five methods that are important:

• setLength: stores a value in the length field

• setWidth: stores a value in the width field

• getLength: returns the value in the length field

• getWidth: returns the value in the width field

• getArea: returns the area of the rectangle

Unit 5 - Classes, Objects and Methods 39

Page 40: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• Collecting all these pieces of information we can build up the UML diagram for the class:

• With this, we are ready to develop the class Rectangle.

Unit 5 - Classes, Objects and Methods 40

Class nameTwo fields

Five methods

Page 41: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• Step 1: We start a new class with the following skeleton:

• The access specifier, public, allows this class to be used by other programs outside the Rectangle.java file.

• The general form:

• Here members refer to the fields and methods that belong to the class.Unit 5 - Classes, Objects and Methods 41

Page 42: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• Step 2: We then declare the variables that represent the fields to be used in this class.

• That is:

• The access specifier, private, means that the class will hide the data within the class, and these variables may not be accessed by statements outside the class.

• This is a common practice to use private fields for security purpose.

Unit 5 - Classes, Objects and Methods 42

Page 43: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• Step 3: Now we can define the methods. Firstly, the method that assign values to the field length.

Unit 5 - Classes, Objects and Methods 43

Access specifier: the keyword public allows this method to be used by other codes outside the class.

Return type: the keyword void is used since this method only performs an action and does not return a value.

Name and variable: this method is called setLength, and requires a variable called len in doubleformat.

Body: the value of the input variable len is assigned to the field length.

Page 44: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• By the same token, the setWidth() method can be defined:

• However, the methods that return the length and width of a rectangle are defined slightly differently:

Unit 5 - Classes, Objects and Methods 44

Instead of void, double is chosen as the return type.

No variable is defined here as this method does not require any input

This method returns the value stored in the field length to the main program

Page 45: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• The other two methods, getWidth() and getArea(), can be defined in a similar way:

Unit 5 - Classes, Objects and Methods 45

The getArea() method makes use of the values stored in the fields to compute the area and returns it to the main program

Page 46: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• Altogether:

Unit 5 - Classes, Objects and Methods 46

public class Rectangle {private double length;private double width;

public void setLength(double len) {length = len;

}public void setWidth(double w) {

width = w;}

public double getLength() {return length;

}public double getWidth() {

return width;}public double getArea() {

return length * width;}

}

Page 47: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• To test the Rectangle class, we run the following program:

Unit 5 - Classes, Objects and Methods 47

public class RectangleDemo {public static void main(String[] args) {

Rectangle box = new Rectangle();

box.setLength(10.0);box.setWidth(20.0);

System.out.println(“The box’s length is ” + box.getLength());System.out.println(“The box’s width is ” + box.getWidth());System.out.println(“The box’s area is ” + box.getArea());

}}

Create an object called box within the Rectangle class

Set the length and width

Print out length, width, and area of the rectangle

Page 48: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• The program produces the following output:

• The getLength() and getWidth() methods are called accessor methods, and the setLegnth() and setWidth() methods are called mutator methods.

• Accessor method: a method that gets a value from a class’s field but does not change it.

• Mutator method: a method that stores a value to a class’s field or changes its value.

Unit 5 - Classes, Objects and Methods 48

Page 49: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• We can show all the specifications of fields (i.e., privacy) and methods (i.e., parameters and data types) of a class in the UML diagram.

• For example, for the Rectangle class that we have just developed:

Unit 5 - Classes, Objects and Methods 49

The privacy of members:+ means public- means private

Parameters and data types:(variable : datatype) : type of method (that means, void or value-return)

Page 50: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• Example: Look at the UML diagram below and answer the following questions:

• What is the name of the class?

• What are the fields?

• What are the methods?

• What are the private members?

• What are the public members?

• Construct a class program based on the UML diagram.

Unit 5 - Classes, Objects and Methods 50

Page 51: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

4. Objects

• Based on the definitions within a class, objects can be created. Each object is called an instance.

• Instances of a class can be created making use of:

1. The constructor

• The instruction by which objects are created.

2. The instance fields

• The data stored and used by the instance.

Unit 5 - Classes, Objects and Methods 51

Page 52: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

A. Constructor

• Constructors are used to create new objects. It includes the executable statements that initialize the fields of the object that it creates.

• A constructor possesses the following items in general:

i. Modifiers, parameters, local variables

ii. Same name as the class itself

iii. No return type

iv. Executable statements that invoke other constructors if needed

Unit 5 - Classes, Objects and Methods 52

Page 53: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• Recall the following class:

Unit 5 - Classes, Objects and Methods 53

public class Point {private int x, y;public Point(int x, int y) {

this.x = x;this.y = y;

}public boolean equals(Point p) {

return (x == p.x && y == p.y);}public int getX() {

return x;}public int getY() {

return y;}public String toString() {

return new String(“(” + x + “, ” + y + “)”);}

}

Page 54: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• The constructor refers to

• We see that:

• The modifier: public

• The parameters: x and y

• The local variables: this.x and this.y

• The name of the constructor: Point

Unit 5 - Classes, Objects and Methods 54

public Point(int x, int y) {this.x = x;this.y = y;

}

Page 55: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• There exists a special type of constructor called default constructorwhich has no argument.

• For example:

• Here, the default constructor creates a Point object that represents the point (5, -2).

Unit 5 - Classes, Objects and Methods 55

public class Point {private int x, y;public Point() {

x = 5;y = -2;

}

// other members

}

Page 56: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• Normally, a default constructor will ensure that the fields of the new object are given natural default values.

• Indeed, all fields in a class will automatically be initialized with their type’s default values unless the constructors explicitly uses other values.

• That is

• Numeric types (e.g., int and double) : 0

• Boolean type : false

• Object variable : null

Unit 5 - Classes, Objects and Methods 56

Page 57: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• If no constructor is defined explicitly, then the compiler will automatically define a public default constructor, initializing all uninitialized fields to their type’s default values.

• For example:

Unit 5 - Classes, Objects and Methods 57

public class Rectangle {private double length;private double width;

public void setLength(double len) {length = len;

}

// other members

}

Page 58: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• When writing the code, the following would be use to call the default constructor and create the object r:

• No argument is needed in this case.

• However, if a constructor is defined explicitly like this:

• Then no object will be produced; instead, an error message will be seen because no arguments are passed to the object.

Unit 5 - Classes, Objects and Methods 58

Page 59: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

B. Instance fields

• Many instances can be created simultaneously for the same class as long as they possess their own data called instance fields.

• For example, for the Rectangle class, the following code creates three objects out of it, each calculating a specific quantity:

Unit 5 - Classes, Objects and Methods 59

Page 60: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• When the three objects are first created, three variables reference the Class object:

Unit 5 - Classes, Objects and Methods 60

Page 61: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• The methods that operate on an instance of a class are called instance methods. They are essentially the methods defined in the class.

• Executing these methods does not need the keyword static.

• Instance method can be invoked by the following statement:

• For example:

• This method receives a value and stores it as the length of the object kitchen in the class.

Unit 5 - Classes, Objects and Methods 61

(object).(class’ method)(variables of the method)

Page 62: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• The data of lengths and widths of these objects can be input in various way, and are assigned and stored accordingly in the objects:

Unit 5 - Classes, Objects and Methods 62

Page 63: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• Two or more methods in a class can share the same name provided their parameter lists are different. This situation is known as method overloading, which is an important feature in modern object-oriented programming.

• For example: these two methods in a class are both called add, and perform the same action

Unit 5 - Classes, Objects and Methods 63

Add two integers

Add two strings

Page 64: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• Java distinguishes these two methods by means of method’s signature which consists of

i. The method’s name

ii. The data types of the method’s parameters in the order that they appear

• That means,

• They have same name but different data types, therefore they are recognized as different methods.

Unit 5 - Classes, Objects and Methods 64

Method’s name Data type of parameters

Page 65: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• Note, however, that the method’s return type is not a part of the method’s signature; therefore, the following two methods cannot be placed in the same class:

• They will be recognized as the same method!Unit 5 - Classes, Objects and Methods 65

Page 66: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• Similarly, constructors could be overloaded in Java. Same rules of method overloading are applied to constructor overloading.

• For example:

• One creates object without argument, and the other creates an object that accepts two arguments.

Unit 5 - Classes, Objects and Methods 66

Page 67: Computer Programming 11/12 - Weebly€¦ · Object-oriented programming •The object-oriented programming (OOP) has become a dominant programming paradigm nowadays, ... •Example:

• These two constructors can be called respectively as follows:

Unit 5 - Classes, Objects and Methods 67