Vous êtes sur la page 1sur 40

introduction to

object
oriented
programming
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

Two popular programming design methods:

• Main problem will • objects as


be divided into foundation for
Structured sub-problems Object problem solving
Programming • Analyze and refine Oriented • Identify objects from
the main problem
each sub-problem
• All sub-problem
Programming • An OOP program is a
solutions are (OOP) collection of objects
that interacts each
implemented as
procedures and other
combined to solves
the main problem
OOP More natural way to solve problem -
Objects represent real-world entities

some related terminologies :

is a blueprint or prototype from which


Class objects are created. Consists of state
and behaviour

is a software bundle of related state and


Object behaviour used to model the real-world
objects. Objects are instances of classes

inheritance A class inherit state and behaviour of


its superclass

objects define their interaction with the


interface outside world via its methods.

package is a namespace for organizing classes and


interfaces in a logical manner. Makes large
SW easier to manage
Objects
An object is a software
bundle of related state
and behavior

state (has various properties, Bicycle’s state (current gear, current


which might change) pedal cadence, current speed)
(general)
Object has: behavior (it can do things &
have things done to it)
Bicycle’s behaviour (changing gear,
changing pedal cadence, applying
brakes)

State (Modifier)
Variable/Data/Field
(OOP) SW
Object has: Method – to do something
on the project/by project
Method can return values - A result
that the method has computed
and returns it to the caller – Can
have 0 or 1 value only

4
concept of objects
object stores its state in fields = variables

exposes its behavior through methods = functions

operate on an object's
internal state
methods primary mechanism for
object-to-object
communication

Hiding internal state


Data and requiring all
interaction to be
encapsulation performed through
an object's methods
example of object Bicycles

Good…
1. Modularity:
The source code for an object can
be written and maintained
independently of the source code
for other objects.

2. Information-hiding:
interaction only with an object's
methods, internal implementation
remain hidden from the outside
world.

3. Code re-use:
can use object written by experts in
your program.

4. Pluggability and debugging


ease:
Can remove and re install parts
easily
classes and objects
Example of Java class:
The String Class
Object

CLASS
Object

Object
description/blue
print of a kind of An object is
object. It does not called an
by itself create instance of a
any objects class
example of class
class Bicycle {

int cadence = 0;
int speed = 0;
int gear = 1;

void changeCadence(int newValue) {


cadence = newValue;
}

void changeGear(int newValue) {


gear = newValue;
}

void speedUp(int increment) {


speed = speed + increment;
}

void applyBrakes(int decrement) {


speed = speed - decrement;
}

void printStates() {
System.out.println("cadence:" +
cadence + " speed:" +
speed + " gear:" + gear);
}
}
creating objects
Notes :

Primitive type variable


(address of value)
vs
Class Object Object reference
(address of object)
Declaration Declaration

Class String <name> Object


Name reference
variable
No object is created with this declaration,
only a location to hold the pointer to object
created (null pointer).

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

All this is called the String constructor, which


is a special method that sets up the object

New creates the object, constructor initialize it


creating bicycles objects

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

// Create two different


// Bicycle objects
Bicycle bike1 = new Bicycle();
cadence:50 speed:10 gear:2
Bicycle bike2 = new Bicycle();
cadence:40 speed:20 gear:3
// Invoke methods on
// those objects
bike1.changeCadence(50);
bike1.speedUp(10);
bike1.changeGear(2);
bike1.printStates();

bike2.changeCadence(50);
bike2.speedUp(10);
bike2.changeGear(2);
bike2.changeCadence(40);
bike2.speedUp(10);
bike2.changeGear(3);
bike2.printStates();
}
}
public class CreateObjectDemo {

public static void main(String[] args) {

// Declare and create a point object and two rectangle objects.

Point originOne = new Point(23, 94);


Rectangle rectOne = new Rectangle(originOne, 100, 200);
Rectangle rectTwo = new Rectangle(50, 100);
// display rectOne's width, height, and area

System.out.println("Width of rectOne: " + rectOne.width);


System.out.println("Height of rectOne: " + rectOne.height);
System.out.println("Area of rectOne: " + rectOne.getArea());
// set rectTwo's position

rectTwo.origin = originOne;

// display rectTwo's position


System.out.println("X Position of rectTwo: " + rectTwo.origin.x);
System.out.println("Y Position of rectTwo: " + rectTwo.origin.y);
// move rectTwo and display its new position
rectTwo.move(40, 72);
System.out.println("X Position of rectTwo: " + rectTwo.origin.x);
System.out.println("Y Position of rectTwo: " + rectTwo.origin.y);
}
}
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”;

12
Constructing String objects
• New String objects are created whenever the String
constructors are used:
String name4 = new String(); // Creates an object
String name5 = new String("Socrates");
String name6 = name4;

13
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

14
Object without object reference
cannot be accessed

String n1 = new String(“Ali“);


new String(“Abu“);

: String
sv1: String

value = “Abu”
value = “Ali”

n1- object reference variable


n1

15
Object References

• Primitive type variables ≠ object variables

16
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
num1 38

name1 "Steve Jobs"

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

• For primitive types:

num1 38
Before:
num2 96

num2 = num1;

num1 38
After:
num2 38 18
Object Reference Assignment
• For object references, assignment copies the
address:
name1 "Steve Jobs"
Before:
name2 "Steve Austin"

name2 = name1;

name1 "Steve Jobs"


After:
name2

19
Questions

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? 20
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
21
Graphical Representation of a
Class
A class can
contain data
declarations and
method
declarations
Class Name
Access
Type of data
Variables

Method Type of
return
A UML Class Diagram value
The notation we used here is based on the industry standard notation
called UML, which stands for Unified Modeling Language.
22
Object Instantiation

class

object

23
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?
24
– These are private.
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 25
UML Design Specification
Instance variables -- memory locations
used for storing the information needed.

Class Name

What data does it need?


Hidden
information
Public What behaviors
methods will it perform?

UML Class Diagram

Methods -- blocks of code used to


perform a specific task.

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

Continued…
27
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

28
Method Control Flow
• If the called method is in the same class, only
the method name is needed

compute myMethod

myMethod();

29
Method Control Flow
• The called method is often part of another
class or object
main doIt helpMe

obj.doIt(); helpMe();

30
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?
31
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 32
Coding into Java
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

33
Method calculatePerimeter()
Algorithm
• Write an algorithm to calculate the
perimeter of a rectangle.
• Write the method in Java.

34
calculatePerimeter()
Algorithm
• Method Name: calculatePerimeter()
• Task: To calculate the perimeter of a
rectangle
• Data Needed (variables)
– length
– width
– perimeter
• Processing: perimeter = 2 x(length + width)
• Result to be returned: perimeter 35
calculatePerimeter() in Java
code
public double calculatePerimeter()
{
double perimeter;
perimeter = 2 * (length + width);

return perimeter;
} // calculatePerimeter()

36
Creating Rectangle Instances
• Create, or instantiate, two instances of the
Rectangle class:
Rectangle rectangle1 = new Rectangle(30,10);
Rectangle rectangle2 = new Rectangle(25, 20);

The objects (instances)


store actual values.

37
Using Rectangle Instances
• We use a method call to ask each object to
tell us its area:
System.out.println("rectangle1 area " + rectangle1.calculateArea());
System.out.println("rectangle2 area " + rectangle2.calculateArea());

References to
Method calls
objects

rectangle1 area 300


Printed output: rectangle2 area 500

38
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.
39
The RectangleUser Class
Definition
Class
Definition
An application must
public class RectangleUser
have a main() method
{
public static void main(String argv[])
Object
{ Creation
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 Object
Use

40

Vous aimerez peut-être aussi