Sei sulla pagina 1di 63

Object Oriented Thinking

Asfar

Object Oriented Concepts


learning OO concepts is not accomplished by learning a specific development method or a set of tools. Doing things in an OO manner is a way of thinking. It is all about the OO thought process. It is important to understand the significant difference between learning OO concepts and using the methods and tools that support the paradigm.

OO Model Examples
Flower, Rose, Read Rose, Yellow Rose, etc Library book, copy etc.

OO(Java, C++)
OO is natural way of representing real world because people already think in terms of objects.
When you look at a person, you see the person as an object. Object is defined by two terms: attributes and behaviors. A person has attributes, such as eye color, age, height, and so on. A person also has behaviors, such as walking, talking, breathing, so, an object is an entity that contains both data and behavior.

The word both is the key difference between OO programming and other programming methodologies.

Procedural(C, Cobol)
In procedural programming, code is placed into totally distinct functions or procedures. Ideally, these procedures then become black boxes, where inputs go in and outputs come out. Data is placed into separate structures and is manipulated by these functions or procedures. Easy to translate to machine instructions (Assembly language)

Object
Everything is an object A program is a bunch of objects Every object has its own memory Every object has a type Object sends messages to other objects Object stores data Can make object requests Object can represent any conceptual component in problem to be solved

Object
A program is a bunch of objects telling each other what to do by sending messages A message is a request to call a method that belongs to a particular object

object
Every object has its own memory made up of other objects Create a new kind of object by making a package consisting of existing objects Build complexity into a program while hiding it behind the simplicity of objects

Class or Type
a class is a blueprint for an object. "Type" is synonymous with "Class" Object is an "instance of a class"

Definition of object
An object has a state, behavior and identity Internal data (state) Methods (behavior) Each object can be uniquely distinguished (unique address in memory)

Attribute
Object attribute describes one of the object characteristics Every attribute has a unique value for a particular object at a specific time State of an object: the values of its attributes at a given time

Whole story
An object has
Attributes and values of attributes = state Operations = behavior

An object is characterized by
Its state and behavior

There are different kinds of objects


Concrete Conceptual Event and State

Object example : Book State in Library


Attributes ID Author Title Price Subject On Loan OBJ 1
(State)

OBJ 2
(State)

OBJ 3
(State)

OBJ 4
(State)

3751 John The Firm 45 17 No

7777 James JAVA 90 07 No

3751 John The Firm 45 17 No

7777 James JAVA 90 07 Yes

Operation/Behavior
Operation
What object can do, or what can be done to the object One of the features of an object

Behavior/Interface
Behavior/Interface of an object equals all of its operations

Example in OOP
Date d = new Date(); d.set(11, "Jan", 2004); N = d.dayOfWeek()
Date - day - month - year + set() + dayOfWeek()

Name of the type/class is Date Name of the object is d Create an object by calling new

Encapsulation
Encapsulation is the mechanism that binds together the code and the data it manipulates, and keeps both safe from outside interference and misuse.

Public variables and methods Private variables and methods Public variables is not recommended

A Class

Encapsulation
Information hiding
All information regarding a module must be private, unless explicitly declared otherwise

Encapsulation
Implementation of information hiding in the world of objects Encapsulation is a central concept of object orientation theory
continued

Encapsulation of Data
Representation of the data is hidden No direct access to data, only via operations Clients of the objects services only know the signature of the service: meaning syntax and semantics of the interface

Class Example in Java


class DATE { // class

private int day; private int month; private int year;

// attribute // attribute // attribute

public setDate(int y, int m, int d) // operation { day=d; // method month=m; year=y; // operation // method

public int getDay( ) { return day; }

Access Designations
When a data type or method is defined as
public, all other objects can directly access it. private, only that specific object can access it. protected, allows access by that specific object and its child objects.

Interface of Object
Each object can satisfy certain requests Object requests are defined by their "interface" Code must satisfy a request (method) Code and hidden data comprise the "Implementation"

OOA
Identify objects/classes Determining the Responsibilities of Each Class
the data that the class must store and operations the class must perform. For example, an Employee object would be responsible
for calculating payroll and transferring money to the appropriate account. for storing the various payroll rates and the account numbers of various banks.

Determining How the Classes Collaborate with Each Other


Although a class must fulfill certain responsibilities, it will have to interact with another class to get something it wants. One class can send a message to another class when it needs information from that class, or if it wants the other class to do something for it.

Abstraction
Convert complex real object to simple SW representation
Identify Attributes, operations

Whether to make a object/attribute depending on the problem SW trying to solve E.g


Person as Employee or husband/wife Flower, Rose, Color

Constructors
Special Methods Methods that share the same name as the class Have no return type When a new object is created, the constructor of its class is called. Usually contains initialization of the attributes Default Constructor Standard: Always provide a constructor Using multiple constructors Java Example

public class Count { int count; public Count() { count = 0; } public Count (int number) { count = number; } }

Java Example

Constructor behavior
First the constructor of the superclass is called. If there is no explicit call to the superclass constructor the default constructor is called The attributes are initialized The rest of the constructor is executed

Overloading Methods
The signature consists of the method name and a parameter list Two different methods can have the same name but not the same signature Usually the signature does not include the return type Java Example

Java Example
public void getCab(); public void getCab (String cabbieName); public void getCab (int numberOfPassengers);

Static Attributes / Operations


The attribute is shared between all objects of a certain class Synonym: Class variable Static operations can not access instance (non-static) attributes

What is Inheritance?
Inheritance clones a class and allows additions and modifications to the clone If the original class is changed, the modified clone reflects the changes Original class is called: Base Class, Superclass, or Parent Class New class is called: Derived Class, Inherited Class, Subclass, or Child Class Usually more than one derived class
continued

What is Inheritance? (cont.)


Base inheritance type contains all characteristics and behaviors shared among the types derived from it Base type example: Shape Derived type examples: Circle, Square, Rectangle Type hierarchy embodies both similarities and differences between the shapes
continued

What is Inheritance? (cont.)


When we inherit from an existing type, we create a new type New type contains all members of existing type and duplicates interface of the base class Derived class is same type as base class: a circle is a shape Ways to differentiate derived classes from base classes

Ways to differentiate derived classes from base classes


Add new methods to the derived class Change the behavior of an existing base-class method: overriding Using same interface method, do something different for new type

Inheritance in UML Diagram


Shape + + + + + draw() erase() move() getColor() setColor()

Circle + draw() + erase() + move()

Square + draw() + erase() + move()

Triangle + draw() + erase() + move()

Object Messages
All objects of same type can receive the same messages Object of type "Circle" is also an object of type "Shape" Circle is guaranteed to accept shape messages "Substitutability" is a powerful Object Oriented concept

Generalization/Specialization
Generalization/Specializ ation
Vehicle
is a kind of

Superclass

Car

Superclass Subclass

Boat

Sports Car

Passenger Car

Truck

Sailing Boat

Motorboat

Cargo Ship

(Subclass) Class

Generalization
Relationship between a general class and more specific class More specific class is fully consistent with the more general class and contains additional information or behavior An instance of the more specific class may be used wherever the more general class can be used

Inheritance Definition
Current class IS A special kind of its superclass When a subclass instance has all attributes and behavior of the superclass instances

Classes Look Up the Hierarchy


Arrows in the class hierarchy point upward from a class to its superclass, not downward from a class to its subclass Directionality
For inheritance to work, classes must know their superclasses If a given class does not contain the definition of a required operation or attribute, it traces its way up the class hierarchy until it finds that definition

Inheritance in Software
Two kinds of inheritance: Full inheritance
Subclass inherits both signature of service (interface) and its implementation (the method) from its superclass

Interface inheritance
Subclass inherits only service signature (interface) from its superclass

Singly Rooted Hierarchy


All classes in Java are inherited from a single base class All objects have a common interface, so all are same fundamental type All objects can be guaranteed to have certain functionality Garbage collector is easiest to implement (necessary support installed in base class) Greater programming flexibility

Polymorphism
Objects from different classes with common superclass can provide service in response to the same message, each object in its own way

Polymorphism Advantages
When dealing with type hierarchies, treat an object as its base type not as its specific type Allows writing code that doesnt depend on specific types Code is unaffected by addition of new types An essential way to encapsulate change Reduces cost of software maintenance

Polymorphism Example
Employee + + + + + + + + + id firstName lastName birthYear status role getAge() setDetails() setId() getId() toString() computeSalary() computeTax1() computeTax2() computeTax3()

Manager + + + + computeSalary() computeTax1() computeTax2() computeTax3() + + + +

Clerk computeSalary() computeTax1() computeTax2() computeTax3() + + + +

Programmer computeSalary() computeTax1() computeTax2() computeTax3()

continued

Which method is called?


What is the problem? At compiling time, the compiler cannot know precisely which piece of code will be executed The function call generated by a non-OOP compiler causes early binding Object-oriented languages use late binding concept to solve the problem

Dynamic(Late) Binding
When a message is sent to an object, the code being called isnt determined until run time Compiler ensures the method exists and checks argument types and return value, but it doesnt know the exact code to execute Java uses a special bit of code to perform late binding
continued

Dynamic(Late) Binding
In some languages you must explicitly state that you want a method to have the flexibility of late-binding properties (C++) In Java, dynamic binding is the default behavior and no need to remember to add any extra keywords in order to get polymorphism The process of treating a derived type as though it were its base type upcasting

Polymorphism Pattern
When related behaviors vary by class, assign responsibility for the behavior to the classes for which the behavior varies Giving the same name to services in different classes when the services are similar The different classes are usually related in a hierarchy with a common superclass, but this is not strictly necessary (interfaces in Java) Recommendation: Do no test for the class of an object and use conditional logic to perform varying alternativess

Abstract Classes
Created only for inheritance purposes Not for use as object Different from concrete class Abstract class cannot be instantiated

Used only to present an interface for its derived classes

continued

Abstract Operations
Used to describe a method that hasnt been implemented Abstract method may be created only inside an abstract class When class is inherited, that method must be implemented, or the inheriting class becomes abstract as well Creating an abstract method allows putting a method in an interface without being forced to provide a code for that method A class that has at least one abstract operation must be abstract A class that inherits from a class that has one or more abstract operations must implement those operations or itself become an abstract classs
continued

Abstract Classes
Fruit

Apples

Oranges

Bananas

Worker

Butcher

Baker

Programmer

Geometrical Shapes
Shape
Select Display

Circle Radius Size


Select Display

>

>

Polygon
Number of Sides Select Display

Interface
Interface is like a class with only abstract methods Provides perfect separation of interface and implementation Many interfaces can be combined together Not possible to inherit from multiple regular classes or abstract classes Type of contract between the interface and the implementor Allow to refer to objects from different classes with the same operation (but different methods)

Composition
objects are often built, or composed, from other objects Example: A computer contains video cards, keyboards, and drives. Although the computer can be considered an object itself, the drive is also considered a valid object. In fact, you could open up the computer and remove the drive

Reusing the Implementation


Code reuse: great advantage of objectoriented programming languages Reuse by Composition: compose a new class from existing classes Relation of type: "has-a"
A car has an engine

Car

Engine

Reuse by Composition
Place an object inside a new class "Compose" a new class from existing classes Relation of type: "has-a"
A car has an engine
Car Engine

Flexibility: member objects in new class are typically private and inaccessible to the client programmers Allows changing members without disturbing existing client code

Relationships
Relationships provide a pathway for communication between objects if two objects need to talk there must be a link between them Three types of relationships are:
Association Aggregation Dependency

Relationships
An association is a bi-directional connection between classes
An association is shown as a line connecting the related classes

An aggregation is a stronger form of relationship where the relationship is between a whole and its parts
An aggregation is shown as a line connecting the related classes with a diamond next to the class representing the whole

A dependency relationship is a weaker form of relationship showing a relationship between a client and a supplier where the client does not have semantic knowledge of the supplier
A dependency is shown as a dashed line pointing from the client to the supplier

Relationships
RegistrationForm RegistrationManager
addStudent(Course, StudentInfo)

ScheduleAlgorithm

Course
name numberCredits

StudentInfo
name major

open() addStudent(StudentInfo)

ProfessorInfo
name tenureStatus

CourseOffering
location open() addStudent(StudentInfo)

Multiplicity and Navigation


Multiplicity defines how many objects participate in a relationships
Multiplicity is the number of instances of one class related to ONE instance of the other class For each association and aggregation, there are two multiplicity decisions to make: one for each end of the relationship

Although associations and aggregations are bidirectional by default, it is often desirable to restrict navigation to one direction
If navigation is restricted, an arrowhead is added to indicate the direction of the navigation

Multiplicity and Navigation


RegistrationForm 0..* 1 RegistrationManager
addStudent(Course, StudentInfo)

ScheduleAlgorithm

1 0..* StudentInfo
major

Course
name numberCredits open() addStudent(StudentInfo)

1 3..10 ProfessorInfo
tenureStatus

4 1 0..4

1..* CourseOffering
location open() addStudent(StudentInfo)

Object Oriented Design OOD


1. Notation (Unified Modeling Language)
Structural description ( class diagrams ) Dynamics ( Collaboration and interaction diagrams )

2. Detailed Class and object description


Visibility (Private, protected, .. ) Persistence Exceptions Containment (ex. Packages ) Concurrency

OOP Goal
Reuse
Reusing analysis and design concepts Reusing implementations

Maintainability Extensibility

Potrebbero piacerti anche