41
Object-Oriented Object-Oriented Programming Programming Concepts Concepts

Object-oriented concepts

Embed Size (px)

DESCRIPTION

OOP lecture concepts

Citation preview

Page 1: Object-oriented concepts

Object-Oriented Object-Oriented Programming Programming

ConceptsConcepts

Page 2: Object-oriented concepts

ContentsContents

1.1. What is OOP?What is OOP?

2.2. Classes and ObjectsClasses and Objects

3.3. Principles of OOPPrinciples of OOP

• InheritanceInheritance

• AbstractionAbstraction

• EncapsulationEncapsulation

• PolymorphismPolymorphism

2

Page 3: Object-oriented concepts

What is OOP?What is OOP?

Page 4: Object-oriented concepts

What is OOP?What is OOP?

• Object-oriented programming (OOP) is an Object-oriented programming (OOP) is an engineering approach for building software engineering approach for building software systemssystems

• Based on the concepts of classes and Based on the concepts of classes and objects that are used for modeling the real objects that are used for modeling the real world entitiesworld entities

• Object-oriented programsObject-oriented programs

• Consist of a group of cooperating objectsConsist of a group of cooperating objects

• Objects exchange messages, for the Objects exchange messages, for the purpose of achieving a common objectivepurpose of achieving a common objective

• Implemented in object-oriented languagesImplemented in object-oriented languages4

Page 5: Object-oriented concepts

OOP in a NutshellOOP in a Nutshell

• A program models a world of interacting A program models a world of interacting objectsobjects

• Objects create other objects and “send Objects create other objects and “send messages” to each other (in Java, call each messages” to each other (in Java, call each other’s methods)other’s methods)

• Each object belongs to a classEach object belongs to a class

• A class defines properties of its objectsA class defines properties of its objects

• The data type of an object is its classThe data type of an object is its class

• Programmers write classes (and reuse existing Programmers write classes (and reuse existing classes)classes)

5

Page 6: Object-oriented concepts

What are OOP’s Claims To What are OOP’s Claims To Fame?Fame?

• Better suited for team developmentBetter suited for team development

• Facilitates utilizing and creating reusable Facilitates utilizing and creating reusable software componentssoftware components

• Easier GUI programmingEasier GUI programming

• Easier software maintenanceEasier software maintenance

• All modern languages are object-oriented: All modern languages are object-oriented: Java, C#, PHP, Perl, C++, ...Java, C#, PHP, Perl, C++, ...

6

Page 7: Object-oriented concepts

Classes and ObjectsClasses and Objects

Page 8: Object-oriented concepts

What Are Objects?What Are Objects?

• Software objects model real-world objects Software objects model real-world objects or abstract conceptsor abstract concepts

• E.g. dog, bicycle, queue E.g. dog, bicycle, queue

• Real-world objects have states and Real-world objects have states and behaviorsbehaviors

• Dogs' states: name, color, breed, hungryDogs' states: name, color, breed, hungry

• Dogs' behaviors: barking, fetching, sleepingDogs' behaviors: barking, fetching, sleeping

8

Page 9: Object-oriented concepts

What Are Objects?What Are Objects?

• How do software objects implement real-How do software objects implement real-world objects?world objects?

• Use variables/data to implement statesUse variables/data to implement states

• Use methods/functions to implement Use methods/functions to implement behaviorsbehaviors

• An object is a software bundle of variables An object is a software bundle of variables and related methodsand related methods

9

Page 10: Object-oriented concepts

10

checkschecks

peoplepeople

shopping listshopping list

……

numbersnumbers

characterscharacters

queuesqueues

arraysarrays

Things in the Things in the real worldreal world

Things in the computercomputer world

Objects Represent

Page 11: Object-oriented concepts

ClassesClasses

• Classes provide the structure for Classes provide the structure for objectsobjects• Define their prototypeDefine their prototype

• Classes define:Classes define:• Set of Set of attributesattributes

• Also called Also called statestate

• Represented by variables and propertiesRepresented by variables and properties

• BehaviorBehavior• Represented by methodsRepresented by methods

• A class defines the methods and types of A class defines the methods and types of data associated with an objectdata associated with an object 11

Page 12: Object-oriented concepts

ObjectsObjects

• Creating an object from a class is called Creating an object from a class is called instantiationinstantiation

• An An objectobject is a concrete is a concrete instanceinstance of a of a particular classparticular class

• Objects have stateObjects have state

• Set of values associated to their attributesSet of values associated to their attributes

• Example:Example:

• Class: AccountClass: Account

• Objects: Ivan's account, Peter's accountObjects: Ivan's account, Peter's account12

Page 13: Object-oriented concepts

Classes – ExampleClasses – Example

13

AccountAccountAccountAccount

+Owner: Person+Owner: Person+Ammount: double+Ammount: double+Owner: Person+Owner: Person+Ammount: double+Ammount: double

+suspend()+suspend()+deposit(sum:double)+deposit(sum:double)+withdraw(sum:double)+withdraw(sum:double)

+suspend()+suspend()+deposit(sum:double)+deposit(sum:double)+withdraw(sum:double)+withdraw(sum:double)

ClassClassClassClassAttributesAttributesAttributesAttributes

OperationsOperationsOperationsOperations

Page 14: Object-oriented concepts

Classes and Objects – Classes and Objects – ExampleExample

14

AccountAccountAccountAccount

+Owner: Person+Owner: Person+Ammount: double+Ammount: double+Owner: Person+Owner: Person+Ammount: double+Ammount: double

+suspend()+suspend()+deposit(sum:double)+deposit(sum:double)+withdraw(sum:double)+withdraw(sum:double)

+suspend()+suspend()+deposit(sum:double)+deposit(sum:double)+withdraw(sum:double)+withdraw(sum:double)

ClassClassClassClass ivanAccountivanAccountivanAccountivanAccount

+Owner="Ivan Kolev"+Owner="Ivan Kolev"+Ammount=5000.0+Ammount=5000.0+Owner="Ivan Kolev"+Owner="Ivan Kolev"+Ammount=5000.0+Ammount=5000.0

peterAccountpeterAccountpeterAccountpeterAccount

+Owner="Peter Kirov"+Owner="Peter Kirov"+Ammount=1825.33+Ammount=1825.33+Owner="Peter Kirov"+Owner="Peter Kirov"+Ammount=1825.33+Ammount=1825.33

kirilAccountkirilAccountkirilAccountkirilAccount

+Owner="Kiril Kirov"+Owner="Kiril Kirov"+Ammount=25.0+Ammount=25.0+Owner="Kiril Kirov"+Owner="Kiril Kirov"+Ammount=25.0+Ammount=25.0

ObjectObjectObjectObject

ObjectObjectObjectObject

ObjectObjectObjectObject

Page 15: Object-oriented concepts

MessagesMessages

• What is a message in OOP?What is a message in OOP?

• A request for an object to perform one of its A request for an object to perform one of its operations (methods)operations (methods)

• All communication between objects is done All communication between objects is done via messagesvia messages

15

Page 16: Object-oriented concepts

InterfacesInterfaces

• Messages define the interface to the objectMessages define the interface to the object

• Everything an object can do is represented Everything an object can do is represented by its message interfaceby its message interface

• The interfaces provide abstractionsThe interfaces provide abstractions

• You shouldn't have to know anything about You shouldn't have to know anything about what is in the implementation in order to use what is in the implementation in order to use it (black box)it (black box)

• An interface is a set of operations An interface is a set of operations (methods) that given object can perform(methods) that given object can perform

16

Page 17: Object-oriented concepts

The Principles of OOPThe Principles of OOP

Page 18: Object-oriented concepts

The Principles of OOPThe Principles of OOP

• InheritanceInheritance

• AbstractionAbstraction

• EncapsulationEncapsulation

• PolymorphismPolymorphism

18

Page 19: Object-oriented concepts

InheritanceInheritance

• A class can A class can extendextend another class, inheriting another class, inheriting all its data members and methodsall its data members and methods• The child class can redefine some of the The child class can redefine some of the

parent class's members and methods and/or parent class's members and methods and/or add its ownadd its own

• A class can A class can implementimplement an interface, an interface, implementing all the specified methodsimplementing all the specified methods

• Inheritance implements the “is a” Inheritance implements the “is a” relationship between objectsrelationship between objects

19

Page 20: Object-oriented concepts

InheritanceInheritance

• TerminologyTerminology

20

subclass

or

derived class

superclass

or

base class

extends

subinterface superinterfaceextends

class interfaceimplements

Page 21: Object-oriented concepts

InheritanceInheritance

21

PersonPersonPersonPerson

+Name: String+Name: String+Address: String+Address: String+Name: String+Name: String+Address: String+Address: String

EmployeeEmployeeEmployeeEmployee

+Company: String+Company: String+Salary: double+Salary: double+Company: String+Company: String+Salary: double+Salary: double

StudentStudentStudentStudent

+School: String+School: String+School: String+School: String

SuperclassSuperclassSuperclassSuperclass

SubclassSubclassSubclassSubclassSubclassSubclassSubclassSubclass

Page 22: Object-oriented concepts

Inheritance in JavaInheritance in Java

• In Java, a subclass can extend only one In Java, a subclass can extend only one superclasssuperclass

• In Java, a subinterface can extend one In Java, a subinterface can extend one superinterfacesuperinterface

• In Java, a class can implement several In Java, a class can implement several interfacesinterfaces

• This is Java’s form of This is Java’s form of multiple inheritancemultiple inheritance

22

Page 23: Object-oriented concepts

Interfaces and Abstract Interfaces and Abstract Classes in JavaClasses in Java

• An abstract class can have code for some An abstract class can have code for some of its methodsof its methods

• Other methods are declared Other methods are declared abstractabstract and left and left with no codewith no code

• An interface only lists methods but does An interface only lists methods but does not have any codenot have any code

• A concrete class may extend an abstract A concrete class may extend an abstract class and/or implement one or several class and/or implement one or several interfaces, supplying the code for all the interfaces, supplying the code for all the methodsmethods 23

Page 24: Object-oriented concepts

Inheritance BenefitsInheritance Benefits

• Inheritance plays a dual role:Inheritance plays a dual role:

• A subclass reuses the code from the A subclass reuses the code from the superclasssuperclass

• A subclass inherits the A subclass inherits the data typedata type of the of the superclass (or interface) as its own superclass (or interface) as its own secondary typesecondary type

24

Page 25: Object-oriented concepts

Class HierarchiesClass Hierarchies

• Inheritance leads to a hierarchy of classes Inheritance leads to a hierarchy of classes and/or interfaces in an application:and/or interfaces in an application:

25

Game

GameFor2

BoardGame

Chess Backgammon

Solitaire

Page 26: Object-oriented concepts

InheritanceInheritance

• An object of a class at the bottom of a An object of a class at the bottom of a hierarchy inherits all the methods of all the hierarchy inherits all the methods of all the classes aboveclasses above

• It also inherits the data types of all the It also inherits the data types of all the classes and interfaces aboveclasses and interfaces above

• Inheritance is also used to extend Inheritance is also used to extend hierarchies of library classeshierarchies of library classes

• Allows reusing the library code and Allows reusing the library code and inheriting library data typesinheriting library data types

26

Page 27: Object-oriented concepts

AbstractionAbstraction

• Abstraction means ignoring irrelevant Abstraction means ignoring irrelevant features, properties, or functions and features, properties, or functions and emphasizing the relevant ones...emphasizing the relevant ones...

• ... relevant to the given project (with an eye ... relevant to the given project (with an eye to future reuse in similar projects)to future reuse in similar projects)

• Abstraction = managing complexityAbstraction = managing complexity27

““Relevant” to what?Relevant” to what?

Page 28: Object-oriented concepts

AbstractionAbstraction

• Abstraction is something we do every dayAbstraction is something we do every day• Looking at an object, we see those things Looking at an object, we see those things

about it that have meaning to usabout it that have meaning to us

• We abstract the properties of the object, and We abstract the properties of the object, and keep only what we needkeep only what we need

• Allows us to represent a complex reality in Allows us to represent a complex reality in terms of a simplified modelterms of a simplified model

• Abstraction highlights the properties of an Abstraction highlights the properties of an entity that we are most interested in and entity that we are most interested in and hides the othershides the others

28

Page 29: Object-oriented concepts

Abstraction in JavaAbstraction in Java

• In Java abstraction is achieved by use ofIn Java abstraction is achieved by use of

• Abstract classes Abstract classes

• InterfacesInterfaces

29

+Color : long

AbstractButton

+click()

«interface»IClickable

Button RadioButton ImageButton

Page 30: Object-oriented concepts

Abstract Data TypesAbstract Data Types

• Abstract Data Types (ADT) are data types Abstract Data Types (ADT) are data types defined by a set of operationsdefined by a set of operations

• Examples:Examples:

30LinkedList

+add(in item : Object)+remove(in item : Object)+clear()

«interface»IList

ArrayList

Page 31: Object-oriented concepts

Abstraction in AWT/SwingAbstraction in AWT/Swing

• java.lang.Objectjava.lang.Object

• ||

• +--java.awt.Component+--java.awt.Component

• ||

• +--java.awt.Container+--java.awt.Container

• ||

• +--javax.swing.JComponent+--javax.swing.JComponent

• ||

• +--javax.swing.+--javax.swing.AbstractButtonAbstractButton31

Page 32: Object-oriented concepts

EncapsulationEncapsulation

• Encapsulation means that all data members Encapsulation means that all data members ((fieldsfields) of a class are declared ) of a class are declared privateprivate

• Some methods may be private, tooSome methods may be private, too

• The class interacts with other classes The class interacts with other classes (called the (called the clientsclients of this class) only of this class) only through the class’s constructors and public through the class’s constructors and public methodsmethods

• Constructors and public methods of a class Constructors and public methods of a class serve as the serve as the interfaceinterface to class’s clients to class’s clients

32

Page 33: Object-oriented concepts

EncapsulationEncapsulation

• Ensures that structural changes remain Ensures that structural changes remain locallocal::

• Usually, the internal structure of a class Usually, the internal structure of a class changes more often than the class’s changes more often than the class’s constructors and methodsconstructors and methods

• Encapsulation ensures that when fields Encapsulation ensures that when fields change, no changes are needed in other change, no changes are needed in other classes (a principle known as “locality”)classes (a principle known as “locality”)

• Hiding implementation details reduces Hiding implementation details reduces complexity complexity easier maintenance easier maintenance 33

Page 34: Object-oriented concepts

Encapsulation – ExampleEncapsulation – Example

• Data Fields are privateData Fields are private

• Constructors and accessor methods are Constructors and accessor methods are defineddefined

34

Page 35: Object-oriented concepts

PolymorphismPolymorphism

• Ability to take more than one formAbility to take more than one form

• A class can be used through its parent A class can be used through its parent class's interfaceclass's interface

• A subclass may override the implementation A subclass may override the implementation of an operation it inherits from a superclass of an operation it inherits from a superclass (late binding)(late binding)

• Polymorphism allows abstract operations Polymorphism allows abstract operations to be defined and usedto be defined and used

• Abstract operations are defined in the base Abstract operations are defined in the base class's interface and implemented in the class's interface and implemented in the subclassessubclasses

35

Page 36: Object-oriented concepts

PolymorphismPolymorphism

• Why use an object as a more generic type?Why use an object as a more generic type?

• To perform abstract operationsTo perform abstract operations

• To mix different related types in the same To mix different related types in the same collectioncollection

• To pass it to a method that expects a To pass it to a method that expects a parameter of a more generic typeparameter of a more generic type

• To declare a more generic field (especially in To declare a more generic field (especially in an abstract class) which will be initialized an abstract class) which will be initialized and “specialized” laterand “specialized” later

36

Page 37: Object-oriented concepts

Polymorphism – ExamplePolymorphism – Example

37

Square::calcSurface() {Square::calcSurface() { return size * size;return size * size;}}

-x : int-y : int-size : int

Square

+calcSurface() : double

Figure

-x : int-y : int-radius : int

Circle

Circle::calcSurface() {Circle::calcSurface() { return PI * radius * return PI * radius * raduis;raduis;}}

Abstract Abstract classclass

Abstract Abstract classclass

Abstract Abstract actionaction

Abstract Abstract actionaction

Concrete Concrete classclass

Concrete Concrete classclass

Overriden Overriden actionaction

Overriden Overriden actionactionOverriden Overriden

actionactionOverriden Overriden

actionaction

Page 38: Object-oriented concepts

PolymorphismPolymorphism

• Polymorphism ensures that the appropriate Polymorphism ensures that the appropriate method is called for an object of a specific method is called for an object of a specific type when the object is disguised as a more type when the object is disguised as a more generic type:generic type:

38

Figure f1 = new Square(...);Figure f1 = new Square(...);Figure f2 = new Circle(...);Figure f2 = new Circle(...);

// This will call Square::calcSurface()// This will call Square::calcSurface()int surface = f1.calcSurface();int surface = f1.calcSurface();

// This will call Square::calcSurface()// This will call Square::calcSurface()int surface = f2.calcSurface();int surface = f2.calcSurface();

Page 39: Object-oriented concepts

Polymorphism in JavaPolymorphism in Java

• Good news: polymorphism is already Good news: polymorphism is already supported in Javasupported in Java

• All you have to do is use it properlyAll you have to do is use it properly

• Polymorphism is implemented using a Polymorphism is implemented using a technique called technique called latelate method bindingmethod binding: :

• Exact method to call is determined at run Exact method to call is determined at run time before performing the calltime before performing the call

39

Page 40: Object-oriented concepts

QuestionsQuestions??

OOP ConceptsOOP Concepts

Page 41: Object-oriented concepts

ProblemsProblems

1.1. Describe the term Describe the term objectobject in OOP. in OOP.

2.2. Describe the term Describe the term classclass in OOP. in OOP.

3.3. Describe the term Describe the term interfaceinterface in OOP. in OOP.

4.4. Describe the term Describe the term inheritanceinheritance in OOP. in OOP.

5.5. Describe the term Describe the term abstractionabstraction in OOP. in OOP.

6.6. Describe the term Describe the term encapsulationencapsulation in OOP. in OOP.

7.7. Describe the term Describe the term polymorphismpolymorphism in OOP. in OOP.

41