Class & Object - Intro

43
Introduction to Object-Oriented Programming

description

Chapter 6-1

Transcript of Class & Object - Intro

Page 1: Class & Object - Intro

Introduction toObject-Oriented Programming

Introduction toObject-Oriented Programming

Page 2: Class & Object - Intro

Problem Solving

The key to designing a solution is breaking it down into manageable pieces

When writing software, we design separate pieces that are responsible for certain parts of the solution

Page 3: Class & Object - Intro

Two popular programming design methods:Structured Programming (SP)Object-Oriented Programming (OOP)

Problem Solving

Page 4: Class & Object - Intro

SP

Procedural based approach Main problem will be divided into sub-

problems Analyze and refine each sub-problem All sub-problem solutions are implemented

as procedures and combined to solves the main problem

Page 5: Class & Object - Intro

Object-Oriented Programming

Object based approach objects as foundation for problem solving

Identify objects from the main problem An OOP program is a collection of objects

that interacts each other

Page 6: Class & Object - Intro

Object-Oriented Programming More natural way to solve problem

Objects can be used to represent real-world entities

For instance, an object might represent a particular employee in a company

Each employee object handles the processing and data management related to that employee

Page 7: Class & Object - Intro

Objects

Object-oriented programs use objects, which

represent real world objects. A real world object is a thing, both tangible and

intangible. An object has:

state (it has various properties, which might change) behaviour (it can do things and can have things done

to it)

7

Page 8: Class & Object - Intro

Objects

OOProgramming software objects Software objects have state

Instance Variable/Data/Field

Software objects have behaviour Method

8

Object’smembers

Page 9: Class & Object - Intro

Objects interactions OOP also involves interactions between

objects through calling (invoking) of methods.

9

Method CallsThe OilSensor object calls the warning() method of the Controller, which then invokes the OilLight TurnOn() method.

Page 10: Class & Object - Intro

Method can Return Values

Return value: A result that the method has computed and returns it to the caller

Can returns 0 or 1 value

Scanner s = new Scanner(System.in);

int num = s.nextInt();

10

Continued…

Page 11: Class & Object - Intro

Classes and Objects

To create an object , we MUST provide a definition/description for it

A class is a description/blue print of a kind of object

It does not by itself create any objects How to create an object ?

An object is called an instance of a class

Object instantiation – process of creating an object

11

Page 12: Class & Object - Intro

Example of Java class:The String Class

12

Page 13: Class & Object - Intro

Creating Objects A variable holds either a primitive type or a reference to

an object

A class name can be used as a type to declare an object reference variable

String name;

No object is created with this declaration

An object reference variable holds the address of an object

The object itself must be created separately

13

Page 14: Class & Object - Intro

Creating Objects Generally, we use the new operator to create an object

14

name = new String (“Ali bin Ahmad");

This calls the String constructor, which isa special method that sets up the object

• Creating an object is called instantiation

• An object is an instance of a particular class

Page 15: Class & Object - Intro

Constructing String objects

Strings stringRef = new String(stringLiteral);

 eg.

String name = new String(“Muhammad Haziq”);

Since strings are used frequently, Java provides a shorthand notation for creating a string:

String name = "Muhammad Haziq”;

15

Page 16: Class & Object - Intro

Constructing String objects New String objects are created whenever the

String constructors are used:

16

String name4 = new String(); // Creates an objectString name5 = new String("Socrates");String name6 = name4;

Page 17: Class & Object - Intro

Invoking Methods We've seen that once an object has been instantiated, we

can use the dot operator to invoke its methods

name.length()

A method may return a value, which can be used in an assignment or expression

count = name.length();

S.o.p(“Num. of char in “ + name+ “=“ + count);

A method invocation can be thought of as asking an object to perform a service

17

Page 18: Class & Object - Intro

Object without object reference cannot be accessed

18

String n1 = new String(“Ali“);new String(“Abu“);

sv1: String : String

value = “Ali” value = “Abu”

n1n1- object reference variable

Page 19: Class & Object - Intro

Object References

Primitive type variables ≠ object variables

19

Page 20: Class & Object - Intro

References Note that a primitive variable contains the value itself,

but an object variable contains the address of the object

An object reference can be thought of as a pointer to the location of the object

Rather than dealing with arbitrary addresses, we often depict a reference graphically

20

"Steve Jobs"name1

num1 38

Page 21: Class & Object - Intro

Assignment Revisited The act of assignment takes a copy of a value and stores it in a

variable

For primitive types:

21

num1 38

num2 96Before:

num2 = num1;

num1 38

num2 38After:

Page 22: Class & Object - Intro

Object Reference Assignment For object references, assignment copies the

address:

22

name2 = name1;

name1

name2Before:

"Steve Jobs"

"Steve Austin"

name1

name2After:

"Steve Jobs"

Page 23: Class & Object - Intro

Questions

23

String stud1 = new String(“Ani”);int studID = 65000;

What does variable stud1 contains?What does variable studID contains?Is this allowed? stud1 = studID;

String stud1; stud1 = new String(“Ani”);stud1 = new String(“Obi”);

How many objects were created by the program? How many reference variables does the program contain?

Page 24: Class & Object - Intro

Writing Classes The programs we’ve written in previous

examples have used classes defined in the Java standard class library

Now we will begin to design programs that rely on classes that we write ourselves

True object-oriented programming is based on defining classes that represent objects with well-defined characteristics and functionality

24

Page 25: Class & Object - Intro

Graphical Representation of a Class

25

The notation we used here is based on the industry standard notation called UML, which stands for Unified Modeling Language.

A UML Class Diagram

Class Name

Variables

Method

Type of data

Access

Type of return value

A class can contain data declarations and method declarations

Page 26: Class & Object - Intro

Object Instantiation

26

class

object

Page 27: Class & Object - Intro

Object Design Questions

What role will the object perform? What data or information will it need?

Look for nouns. Which actions will it take?

Look for verbs. What interface will it present to other objects?

These are public methods. What information will it hide from other objects?

These are private.

27

Page 28: Class & Object - Intro

Design Specification for a Rectangle Class Name: Rectangle Role: To represent a geometric rectangle States (Information or instance variables)

- Length: A variable to store rectangle’s length (private)- Width: A variable to store rectangle's width (private)

Behaviors (public methods)- Rectangle(): A constructor method to set a rectangle’s

length and width- calculateArea(): A method to calculate a rectangle’s

area

28

Page 29: Class & Object - Intro

UML Design Specification

29

UML Class Diagram

Class Name

What data does it need?

What behaviors will it perform?

Publicmethods

Hiddeninformation

Instance variables -- memory locations used for storing the information needed.

Methods -- blocks of code used to perform a specific task.

Page 30: Class & Object - Intro

Method can has input (parameter) & output (return value) Parameter : value given to method so that it can

do its task Can has 0 or more parameter Return value: A result that the method has

computed and returns it to the caller Can returns 0 or 1 value Eg. - pow(2,3)

- calculateArea()

- getBalance( ) - move( )

30

Continued…

Page 31: Class & Object - Intro

Method Declarations A method declaration specifies the code that will

be executed when the method is invoked (called)

When a method is invoked, the flow of control jumps to the method and executes its code

When complete, the flow returns to the place where the method was called and continues

The invocation may or may not return a value, depending on how the method is defined

31

Page 32: Class & Object - Intro

Method Control Flow If the called method is in the same class, only the

method name is needed

32

myMethod();

myMethodcompute

Page 33: Class & Object - Intro

Method Control Flow The called method is often part of another class or object

33

doIt

helpMe

helpMe();

obj.doIt();

main

Page 34: Class & Object - Intro

Method Design

What specific task will the method perform? What input data will it need to perform its

task? What result will the method produce? How input data are processed into result? What algorithm will the method use?

34

Page 35: Class & Object - Intro

Method calculateArea() Algorithm Method Name: calculateArea() Task: To calculate the area of a rectangle Data Needed (variables)

length: A variable to store the rectangle's length width: A variable to store the rectangle's width area: A variable to store result of calculation

Processing: area = length x width Result to be returned: area

35

Page 36: Class & Object - Intro

Coding into Java

36

public class Rectangle // Class header{ private double length; // Instance variables private double width; public Rectangle(double l, double w) // Constructor method { length = l; width = w; }

public double calculateArea() // calculate area method { double area;

area = length * width;

return area; } // calculateArea()

} // Rectangle class

Page 37: Class & Object - Intro

Method calculatePerimeter() Algorithm Write an algorithm to calculate the perimeter

of a rectangle. Write the method in Java.

37

Page 38: Class & Object - Intro

calculatePerimeter() Algorithm Method Name: calculatePerimeter() Task: To calculate the perimeter of a

rectangle Data Needed (variables)

lengthwidthperimeter

Processing: perimeter = 2 x(length + width) Result to be returned: perimeter

38

Page 39: Class & Object - Intro

calculatePerimeter() in Java code

39

public double calculatePerimeter()

{

double perimeter;

perimeter = 2 * (length + width);

return perimeter;

} // calculatePerimeter()

Page 40: Class & Object - Intro

Creating Rectangle Instances Create, or instantiate, two instances of the Rectangle class:

40

The objects (instances) store actual values.

Rectangle rectangle1 = new Rectangle(30,10);

Rectangle rectangle2 = new Rectangle(25, 20);

Page 41: Class & Object - Intro

Using Rectangle Instances We use a method call to ask each object to tell us

its area:

41

rectangle1 area 300rectangle2 area 500Printed output:

System.out.println("rectangle1 area " + rectangle1.calculateArea());

System.out.println("rectangle2 area " + rectangle2.calculateArea());

References to objects

Method calls

Page 42: Class & Object - Intro

Syntax : Object Construction new ClassName(parameters);

Example: new Rectangle(30, 20); new Car("BMW 540ti", 2004);

Purpose: To construct a new object, initialize it with the

construction parameters, and return a reference to the constructed object.

42

Page 43: Class & Object - Intro

The RectangleUser Class Definition

public class RectangleUser{ public static void main(String argv[]) { Rectangle rectangle1 = new Rectangle(30,10); Rectangle rectangle2 = new Rectangle(25,20); System.out.println("rectangle1 area " + rectangle1.calculateArea()); System.out.println("rectangle2 area " + rectangle2.calculateArea()); } // main()} // RectangleUser

43

An application must have a main() method

Object Use

ObjectCreation

ClassDefinition