SlideShare a Scribd company logo
1 of 41
Object-OrientedObject-Oriented
ProgrammingProgramming
ConceptsConcepts
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
What is OOP?What is OOP?
What is OOP?What is OOP?
• Object-oriented programming (OOP) is anObject-oriented programming (OOP) is an
engineering approach for building softwareengineering approach for building software
systemssystems
• Based on the concepts of classes andBased on the concepts of classes and
objects that are used for modeling the realobjects 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 theObjects exchange messages, for the
purpose of achieving a common objectivepurpose of achieving a common objective
• Implemented in object-oriented languagesImplemented in object-oriented languages
4
OOP in a NutshellOOP in a Nutshell
• A program models a world of interactingA program models a world of interacting
objectsobjects
• Objects create other objects and “sendObjects create other objects and “send
messages” to each other (in Java, call eachmessages” 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 existingProgrammers write classes (and reuse existing
classes)classes)
5
What are OOP’s Claims ToWhat are OOP’s Claims To
Fame?Fame?
• Better suited for team developmentBetter suited for team development
• Facilitates utilizing and creating reusableFacilitates 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
Classes and ObjectsClasses and Objects
What Are Objects?What Are Objects?
• Software objects model real-world objectsSoftware objects model real-world objects
or abstract conceptsor abstract concepts
• E.g. dog, bicycle, queueE.g. dog, bicycle, queue
• Real-world objects have states andReal-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
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 implementUse methods/functions to implement
behaviorsbehaviors
• An object is a software bundle of variablesAn object is a software bundle of variables
and related methodsand related methods
9
10
checkschecks
peoplepeople
shopping listshopping list
……
numbersnumbers
characterscharacters
queuesqueues
arraysarrays
Things in theThings in the
real worldreal world
Things in the
computercomputer world
Objects Represent
ClassesClasses
• Classes provide the structure forClasses provide the structure for objectsobjects
• Define their prototypeDefine their prototype
• Classes define:Classes define:
• Set ofSet of attributesattributes
• Also calledAlso called statestate
• Represented by variables and propertiesRepresented by variables and properties
• BehaviorBehavior
• Represented by methodsRepresented by methods
• A class defines the methods and types ofA class defines the methods and types of
data associated with an objectdata associated with an object 11
ObjectsObjects
• Creating an object from a class is calledCreating an object from a class is called
instantiationinstantiation
• AnAn objectobject is a concreteis a concrete instanceinstance of aof 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 account
12
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)
ClassClassClassClass
AttributesAttributesAttributesAttributes
OperationsOperationsOperationsOperations
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
MessagesMessages
• What is a message in OOP?What is a message in OOP?
• A request for an object to perform one of itsA request for an object to perform one of its
operations (methods)operations (methods)
• All communication between objects is doneAll communication between objects is done
via messagesvia messages
15
InterfacesInterfaces
• Messages define the interface to the objectMessages define the interface to the object
• Everything an object can do is representedEverything 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 aboutYou shouldn't have to know anything about
what is in the implementation in order to usewhat is in the implementation in order to use
it (black box)it (black box)
• An interface is a set of operationsAn interface is a set of operations
(methods) that given object can perform(methods) that given object can perform
16
The Principles of OOPThe Principles of OOP
The Principles of OOPThe Principles of OOP
• InheritanceInheritance
• AbstractionAbstraction
• EncapsulationEncapsulation
• PolymorphismPolymorphism
18
InheritanceInheritance
• A class canA class can extendextend another class, inheritinganother class, inheriting
all its data members and methodsall its data members and methods
• The child class can redefine some of theThe child class can redefine some of the
parent class's members and methods and/orparent class's members and methods and/or
add its ownadd its own
• A class canA 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
InheritanceInheritance
• TerminologyTerminology
20
subclass
or
derived class
superclass
or
base class
extends
subinterface superinterfaceextends
class interfaceimplements
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
Inheritance in JavaInheritance in Java
• In Java, a subclass can extend only oneIn Java, a subclass can extend only one
superclasssuperclass
• In Java, a subinterface can extend oneIn Java, a subinterface can extend one
superinterfacesuperinterface
• In Java, a class can implement severalIn Java, a class can implement several
interfacesinterfaces
• This is Java’s form ofThis is Java’s form of multiple inheritancemultiple inheritance
22
Interfaces and AbstractInterfaces and Abstract
Classes in JavaClasses in Java
• An abstract class can have code for someAn abstract class can have code for some
of its methodsof its methods
• Other methods are declaredOther methods are declared abstractabstract and leftand left
with no codewith no code
• An interface only lists methods but doesAn interface only lists methods but does
not have any codenot have any code
• A concrete class may extend an abstractA concrete class may extend an abstract
class and/or implement one or severalclass and/or implement one or several
interfaces, supplying the code for all theinterfaces, supplying the code for all the
methodsmethods 23
Inheritance BenefitsInheritance Benefits
• Inheritance plays a dual role:Inheritance plays a dual role:
• A subclass reuses the code from theA subclass reuses the code from the
superclasssuperclass
• A subclass inherits theA subclass inherits the data typedata type of theof the
superclass (or interface) as its ownsuperclass (or interface) as its own
secondary typesecondary type
24
Class HierarchiesClass Hierarchies
• Inheritance leads to a hierarchy of classesInheritance 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
InheritanceInheritance
• An object of a class at the bottom of aAn object of a class at the bottom of a
hierarchy inherits all the methods of all thehierarchy inherits all the methods of all the
classes aboveclasses above
• It also inherits the data types of all theIt also inherits the data types of all the
classes and interfaces aboveclasses and interfaces above
• Inheritance is also used to extendInheritance is also used to extend
hierarchies of library classeshierarchies of library classes
• Allows reusing the library code andAllows reusing the library code and
inheriting library data typesinheriting library data types
26
AbstractionAbstraction
• Abstraction means ignoring irrelevantAbstraction means ignoring irrelevant
features, properties, or functions andfeatures, 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?
AbstractionAbstraction
• Abstraction is something we do every dayAbstraction is something we do every day
• Looking at an object, we see those thingsLooking 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, andWe abstract the properties of the object, and
keep only what we needkeep only what we need
• Allows us to represent a complex reality inAllows us to represent a complex reality in
terms of a simplified modelterms of a simplified model
• Abstraction highlights the properties of anAbstraction highlights the properties of an
entity that we are most interested in andentity that we are most interested in and
hides the othershides the others
28
Abstraction in JavaAbstraction in Java
• In Java abstraction is achieved by use ofIn Java abstraction is achieved by use of
• Abstract classesAbstract classes
• InterfacesInterfaces
29
Abstract Data TypesAbstract Data Types
• Abstract Data Types (ADT) are data typesAbstract Data Types (ADT) are data types
defined by a set of operationsdefined by a set of operations
• Examples:Examples:
30
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.AbstractButtonAbstractButton
31
EncapsulationEncapsulation
• Encapsulation means that all data membersEncapsulation 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 classesThe class interacts with other classes
(called the(called the clientsclients of this class) onlyof this class) only
through the class’s constructors and publicthrough the class’s constructors and public
methodsmethods
• Constructors and public methods of a classConstructors and public methods of a class
serve as theserve as the interfaceinterface to class’s clientsto class’s clients
32
EncapsulationEncapsulation
• Ensures that structural changes remainEnsures that structural changes remain
locallocal::
• Usually, the internal structure of a classUsually, the internal structure of a class
changes more often than the class’schanges more often than the class’s
constructors and methodsconstructors and methods
• Encapsulation ensures that when fieldsEncapsulation ensures that when fields
change, no changes are needed in otherchange, no changes are needed in other
classes (a principle known as “locality”)classes (a principle known as “locality”)
• Hiding implementation details reducesHiding implementation details reduces
complexitycomplexity  easier maintenanceeasier maintenance 33
Encapsulation – ExampleEncapsulation – Example
• Data Fields are privateData Fields are private
• Constructors and accessor methods areConstructors and accessor methods are
defineddefined
34
PolymorphismPolymorphism
• Ability to take more than one formAbility to take more than one form
• A class can be used through its parentA class can be used through its parent
class's interfaceclass's interface
• A subclass may override the implementationA subclass may override the implementation
of an operation it inherits from a superclassof an operation it inherits from a superclass
(late binding)(late binding)
• Polymorphism allows abstract operationsPolymorphism allows abstract operations
to be defined and usedto be defined and used
• Abstract operations are defined in the baseAbstract operations are defined in the base
class's interface and implemented in theclass's interface and implemented in the
subclassessubclasses
35
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 sameTo mix different related types in the same
collectioncollection
• To pass it to a method that expects aTo 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 inTo declare a more generic field (especially in
an abstract class) which will be initializedan abstract class) which will be initialized
and “specialized” laterand “specialized” later
36
Polymorphism – ExamplePolymorphism – Example
37
Square::calcSurface() {Square::calcSurface() {
return size * size;return size * size;
}}
Circle::calcSurface() {Circle::calcSurface() {
return PI * radius *return PI * radius *
raduis;raduis;
}}
AbstractAbstract
classclass
AbstractAbstract
classclass
AbstractAbstract
actionaction
AbstractAbstract
actionaction
ConcreteConcrete
classclass
ConcreteConcrete
classclass
OverridenOverriden
actionaction
OverridenOverriden
actionaction
OverridenOverriden
actionaction
OverridenOverriden
actionaction
PolymorphismPolymorphism
• Polymorphism ensures that the appropriatePolymorphism ensures that the appropriate
method is called for an object of a specificmethod is called for an object of a specific
type when the object is disguised as a moretype 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();
Polymorphism in JavaPolymorphism in Java
• Good news: polymorphism is alreadyGood 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 aPolymorphism is implemented using a
technique calledtechnique called latelate method bindingmethod binding::
• Exact method to call is determined at runExact method to call is determined at run
time before performing the calltime before performing the call
39
QuestionsQuestions??
OOP ConceptsOOP Concepts
ProblemsProblems
1.1. Describe the termDescribe the term objectobject in OOP.in OOP.
2.2. Describe the termDescribe the term classclass in OOP.in OOP.
3.3. Describe the termDescribe the term interfaceinterface in OOP.in OOP.
4.4. Describe the termDescribe the term inheritanceinheritance in OOP.in OOP.
5.5. Describe the termDescribe the term abstractionabstraction in OOP.in OOP.
6.6. Describe the termDescribe the term encapsulationencapsulation in OOP.in OOP.
7.7. Describe the termDescribe the term polymorphismpolymorphism in OOP.in OOP.
41

More Related Content

What's hot

Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaTech_MX
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaMadishetty Prathibha
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programmingAmit Soni (CTFL)
 
Principles and advantages of oop ppt
Principles and advantages of oop pptPrinciples and advantages of oop ppt
Principles and advantages of oop pptdaxesh chauhan
 
object oriented Programming ppt
object oriented Programming pptobject oriented Programming ppt
object oriented Programming pptNitesh Dubey
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming languageMd.Al-imran Roton
 
Java Data Types
Java Data TypesJava Data Types
Java Data TypesSpotle.ai
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsJulie Iskander
 
Introduction to oop
Introduction to oopIntroduction to oop
Introduction to oopcolleges
 
Need of object oriented programming
Need of object oriented programmingNeed of object oriented programming
Need of object oriented programmingAmar Jukuntla
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++Muhammad Waqas
 
1 unit (oops)
1 unit (oops)1 unit (oops)
1 unit (oops)Jay Patel
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented ProgrammingRAJU MAKWANA
 

What's hot (20)

Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Oop Presentation
Oop PresentationOop Presentation
Oop Presentation
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in Java
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Principles and advantages of oop ppt
Principles and advantages of oop pptPrinciples and advantages of oop ppt
Principles and advantages of oop ppt
 
object oriented Programming ppt
object oriented Programming pptobject oriented Programming ppt
object oriented Programming ppt
 
Class diagrams
Class diagramsClass diagrams
Class diagrams
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming language
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Introduction to oop
Introduction to oopIntroduction to oop
Introduction to oop
 
Need of object oriented programming
Need of object oriented programmingNeed of object oriented programming
Need of object oriented programming
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
 
Ooad unit – 1 introduction
Ooad unit – 1 introductionOoad unit – 1 introduction
Ooad unit – 1 introduction
 
1 unit (oops)
1 unit (oops)1 unit (oops)
1 unit (oops)
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 

Similar to Object-oriented concepts

Software Engineering Lec5 oop-uml-i
Software Engineering Lec5 oop-uml-iSoftware Engineering Lec5 oop-uml-i
Software Engineering Lec5 oop-uml-iTaymoor Nazmy
 
C++ programming Assignment Help
C++ programming Assignment HelpC++ programming Assignment Help
C++ programming Assignment Helpsmithjonny9876
 
Object Oriented Paradigm
Object Oriented ParadigmObject Oriented Paradigm
Object Oriented ParadigmHüseyin Ergin
 
James Coplien - Trygve - October 17, 2016
James Coplien - Trygve - October 17, 2016James Coplien - Trygve - October 17, 2016
James Coplien - Trygve - October 17, 2016Foo Café Copenhagen
 
Summer Training Project On C++
Summer Training Project On  C++Summer Training Project On  C++
Summer Training Project On C++KAUSHAL KUMAR JHA
 
Introduction to object oriented programming
Introduction to object oriented programmingIntroduction to object oriented programming
Introduction to object oriented programmingAbzetdin Adamov
 
OOP History and Core Concepts
OOP History and Core ConceptsOOP History and Core Concepts
OOP History and Core ConceptsNghia Bui Van
 
introduction of Object oriented programming
introduction of Object oriented programmingintroduction of Object oriented programming
introduction of Object oriented programmingRiturajJain8
 
The best system for object-oriented thinking
The best system for object-oriented thinkingThe best system for object-oriented thinking
The best system for object-oriented thinkingPharo
 
M01_OO_Intro.ppt
M01_OO_Intro.pptM01_OO_Intro.ppt
M01_OO_Intro.pptRojaPogul1
 
Introducción al Análisis y Diseño Orientado a Objetos
Introducción al Análisis y Diseño Orientado a ObjetosIntroducción al Análisis y Diseño Orientado a Objetos
Introducción al Análisis y Diseño Orientado a ObjetosUniversidad de Occidente
 
Improving Pharo Snapshots
Improving Pharo SnapshotsImproving Pharo Snapshots
Improving Pharo SnapshotsESUG
 
Introduction to Machine Learning
Introduction to Machine LearningIntroduction to Machine Learning
Introduction to Machine LearningRahul Jain
 
Intro to oop.pptx
Intro to oop.pptxIntro to oop.pptx
Intro to oop.pptxUmerUmer25
 
Object oriented software engineering concepts
Object oriented software engineering conceptsObject oriented software engineering concepts
Object oriented software engineering conceptsKomal Singh
 
Object oriented programming concepts
Object oriented programming conceptsObject oriented programming concepts
Object oriented programming conceptsrahuld115
 
Object oriented programming concepts
Object oriented programming conceptsObject oriented programming concepts
Object oriented programming conceptsrahuld115
 

Similar to Object-oriented concepts (20)

Software Engineering Lec5 oop-uml-i
Software Engineering Lec5 oop-uml-iSoftware Engineering Lec5 oop-uml-i
Software Engineering Lec5 oop-uml-i
 
Introduction to c ++ part -1
Introduction to c ++   part -1Introduction to c ++   part -1
Introduction to c ++ part -1
 
C++ programming Assignment Help
C++ programming Assignment HelpC++ programming Assignment Help
C++ programming Assignment Help
 
Object Oriented Paradigm
Object Oriented ParadigmObject Oriented Paradigm
Object Oriented Paradigm
 
James Coplien - Trygve - October 17, 2016
James Coplien - Trygve - October 17, 2016James Coplien - Trygve - October 17, 2016
James Coplien - Trygve - October 17, 2016
 
Summer Training Project On C++
Summer Training Project On  C++Summer Training Project On  C++
Summer Training Project On C++
 
Introduction to object oriented programming
Introduction to object oriented programmingIntroduction to object oriented programming
Introduction to object oriented programming
 
OOP History and Core Concepts
OOP History and Core ConceptsOOP History and Core Concepts
OOP History and Core Concepts
 
introduction of Object oriented programming
introduction of Object oriented programmingintroduction of Object oriented programming
introduction of Object oriented programming
 
The best system for object-oriented thinking
The best system for object-oriented thinkingThe best system for object-oriented thinking
The best system for object-oriented thinking
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
M01_OO_Intro.ppt
M01_OO_Intro.pptM01_OO_Intro.ppt
M01_OO_Intro.ppt
 
Introducción al Análisis y Diseño Orientado a Objetos
Introducción al Análisis y Diseño Orientado a ObjetosIntroducción al Análisis y Diseño Orientado a Objetos
Introducción al Análisis y Diseño Orientado a Objetos
 
Improving Pharo Snapshots
Improving Pharo SnapshotsImproving Pharo Snapshots
Improving Pharo Snapshots
 
Introduction to Machine Learning
Introduction to Machine LearningIntroduction to Machine Learning
Introduction to Machine Learning
 
Intro to oop.pptx
Intro to oop.pptxIntro to oop.pptx
Intro to oop.pptx
 
Object oriented software engineering concepts
Object oriented software engineering conceptsObject oriented software engineering concepts
Object oriented software engineering concepts
 
Object oriented programming concepts
Object oriented programming conceptsObject oriented programming concepts
Object oriented programming concepts
 
Object oriented programming concepts
Object oriented programming conceptsObject oriented programming concepts
Object oriented programming concepts
 
07slide.ppt
07slide.ppt07slide.ppt
07slide.ppt
 

More from BG Java EE Course (20)

Rich faces
Rich facesRich faces
Rich faces
 
JSP Custom Tags
JSP Custom TagsJSP Custom Tags
JSP Custom Tags
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - Basics
 
JSTL
JSTLJSTL
JSTL
 
Unified Expression Language
Unified Expression LanguageUnified Expression Language
Unified Expression Language
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Web Applications and Deployment
Web Applications and DeploymentWeb Applications and Deployment
Web Applications and Deployment
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
CSS
CSSCSS
CSS
 
HTML: Tables and Forms
HTML: Tables and FormsHTML: Tables and Forms
HTML: Tables and Forms
 
HTML Fundamentals
HTML FundamentalsHTML Fundamentals
HTML Fundamentals
 
WWW and HTTP
WWW and HTTPWWW and HTTP
WWW and HTTP
 
JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery Fundamentals
 
Creating Web Sites with HTML and CSS
Creating Web Sites with HTML and CSSCreating Web Sites with HTML and CSS
Creating Web Sites with HTML and CSS
 
Processing XML with Java
Processing XML with JavaProcessing XML with Java
Processing XML with Java
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
 
Introduction to-RDBMS-systems
Introduction to-RDBMS-systemsIntroduction to-RDBMS-systems
Introduction to-RDBMS-systems
 

Recently uploaded

ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
TEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxTEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxruthvilladarez
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEaurabinda banchhor
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Presentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxPresentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxRosabel UA
 
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...liera silvan
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSMae Pangan
 

Recently uploaded (20)

ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
TEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxTEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docx
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Dust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSEDust Of Snow By Robert Frost Class-X English CBSE
Dust Of Snow By Robert Frost Class-X English CBSE
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Presentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxPresentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptx
 
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...
EmpTech Lesson 18 - ICT Project for Website Traffic Statistics and Performanc...
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Textual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHSTextual Evidence in Reading and Writing of SHS
Textual Evidence in Reading and Writing of SHS
 

Object-oriented concepts

  • 2. 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
  • 4. What is OOP?What is OOP? • Object-oriented programming (OOP) is anObject-oriented programming (OOP) is an engineering approach for building softwareengineering approach for building software systemssystems • Based on the concepts of classes andBased on the concepts of classes and objects that are used for modeling the realobjects 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 theObjects exchange messages, for the purpose of achieving a common objectivepurpose of achieving a common objective • Implemented in object-oriented languagesImplemented in object-oriented languages 4
  • 5. OOP in a NutshellOOP in a Nutshell • A program models a world of interactingA program models a world of interacting objectsobjects • Objects create other objects and “sendObjects create other objects and “send messages” to each other (in Java, call eachmessages” 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 existingProgrammers write classes (and reuse existing classes)classes) 5
  • 6. What are OOP’s Claims ToWhat are OOP’s Claims To Fame?Fame? • Better suited for team developmentBetter suited for team development • Facilitates utilizing and creating reusableFacilitates 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
  • 8. What Are Objects?What Are Objects? • Software objects model real-world objectsSoftware objects model real-world objects or abstract conceptsor abstract concepts • E.g. dog, bicycle, queueE.g. dog, bicycle, queue • Real-world objects have states andReal-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
  • 9. 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 implementUse methods/functions to implement behaviorsbehaviors • An object is a software bundle of variablesAn object is a software bundle of variables and related methodsand related methods 9
  • 10. 10 checkschecks peoplepeople shopping listshopping list …… numbersnumbers characterscharacters queuesqueues arraysarrays Things in theThings in the real worldreal world Things in the computercomputer world Objects Represent
  • 11. ClassesClasses • Classes provide the structure forClasses provide the structure for objectsobjects • Define their prototypeDefine their prototype • Classes define:Classes define: • Set ofSet of attributesattributes • Also calledAlso called statestate • Represented by variables and propertiesRepresented by variables and properties • BehaviorBehavior • Represented by methodsRepresented by methods • A class defines the methods and types ofA class defines the methods and types of data associated with an objectdata associated with an object 11
  • 12. ObjectsObjects • Creating an object from a class is calledCreating an object from a class is called instantiationinstantiation • AnAn objectobject is a concreteis a concrete instanceinstance of aof 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 account 12
  • 13. 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) ClassClassClassClass AttributesAttributesAttributesAttributes OperationsOperationsOperationsOperations
  • 14. 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
  • 15. MessagesMessages • What is a message in OOP?What is a message in OOP? • A request for an object to perform one of itsA request for an object to perform one of its operations (methods)operations (methods) • All communication between objects is doneAll communication between objects is done via messagesvia messages 15
  • 16. InterfacesInterfaces • Messages define the interface to the objectMessages define the interface to the object • Everything an object can do is representedEverything 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 aboutYou shouldn't have to know anything about what is in the implementation in order to usewhat is in the implementation in order to use it (black box)it (black box) • An interface is a set of operationsAn interface is a set of operations (methods) that given object can perform(methods) that given object can perform 16
  • 17. The Principles of OOPThe Principles of OOP
  • 18. The Principles of OOPThe Principles of OOP • InheritanceInheritance • AbstractionAbstraction • EncapsulationEncapsulation • PolymorphismPolymorphism 18
  • 19. InheritanceInheritance • A class canA class can extendextend another class, inheritinganother class, inheriting all its data members and methodsall its data members and methods • The child class can redefine some of theThe child class can redefine some of the parent class's members and methods and/orparent class's members and methods and/or add its ownadd its own • A class canA 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
  • 20. InheritanceInheritance • TerminologyTerminology 20 subclass or derived class superclass or base class extends subinterface superinterfaceextends class interfaceimplements
  • 21. 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
  • 22. Inheritance in JavaInheritance in Java • In Java, a subclass can extend only oneIn Java, a subclass can extend only one superclasssuperclass • In Java, a subinterface can extend oneIn Java, a subinterface can extend one superinterfacesuperinterface • In Java, a class can implement severalIn Java, a class can implement several interfacesinterfaces • This is Java’s form ofThis is Java’s form of multiple inheritancemultiple inheritance 22
  • 23. Interfaces and AbstractInterfaces and Abstract Classes in JavaClasses in Java • An abstract class can have code for someAn abstract class can have code for some of its methodsof its methods • Other methods are declaredOther methods are declared abstractabstract and leftand left with no codewith no code • An interface only lists methods but doesAn interface only lists methods but does not have any codenot have any code • A concrete class may extend an abstractA concrete class may extend an abstract class and/or implement one or severalclass and/or implement one or several interfaces, supplying the code for all theinterfaces, supplying the code for all the methodsmethods 23
  • 24. Inheritance BenefitsInheritance Benefits • Inheritance plays a dual role:Inheritance plays a dual role: • A subclass reuses the code from theA subclass reuses the code from the superclasssuperclass • A subclass inherits theA subclass inherits the data typedata type of theof the superclass (or interface) as its ownsuperclass (or interface) as its own secondary typesecondary type 24
  • 25. Class HierarchiesClass Hierarchies • Inheritance leads to a hierarchy of classesInheritance 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
  • 26. InheritanceInheritance • An object of a class at the bottom of aAn object of a class at the bottom of a hierarchy inherits all the methods of all thehierarchy inherits all the methods of all the classes aboveclasses above • It also inherits the data types of all theIt also inherits the data types of all the classes and interfaces aboveclasses and interfaces above • Inheritance is also used to extendInheritance is also used to extend hierarchies of library classeshierarchies of library classes • Allows reusing the library code andAllows reusing the library code and inheriting library data typesinheriting library data types 26
  • 27. AbstractionAbstraction • Abstraction means ignoring irrelevantAbstraction means ignoring irrelevant features, properties, or functions andfeatures, 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?
  • 28. AbstractionAbstraction • Abstraction is something we do every dayAbstraction is something we do every day • Looking at an object, we see those thingsLooking 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, andWe abstract the properties of the object, and keep only what we needkeep only what we need • Allows us to represent a complex reality inAllows us to represent a complex reality in terms of a simplified modelterms of a simplified model • Abstraction highlights the properties of anAbstraction highlights the properties of an entity that we are most interested in andentity that we are most interested in and hides the othershides the others 28
  • 29. Abstraction in JavaAbstraction in Java • In Java abstraction is achieved by use ofIn Java abstraction is achieved by use of • Abstract classesAbstract classes • InterfacesInterfaces 29
  • 30. Abstract Data TypesAbstract Data Types • Abstract Data Types (ADT) are data typesAbstract Data Types (ADT) are data types defined by a set of operationsdefined by a set of operations • Examples:Examples: 30
  • 31. 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.AbstractButtonAbstractButton 31
  • 32. EncapsulationEncapsulation • Encapsulation means that all data membersEncapsulation 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 classesThe class interacts with other classes (called the(called the clientsclients of this class) onlyof this class) only through the class’s constructors and publicthrough the class’s constructors and public methodsmethods • Constructors and public methods of a classConstructors and public methods of a class serve as theserve as the interfaceinterface to class’s clientsto class’s clients 32
  • 33. EncapsulationEncapsulation • Ensures that structural changes remainEnsures that structural changes remain locallocal:: • Usually, the internal structure of a classUsually, the internal structure of a class changes more often than the class’schanges more often than the class’s constructors and methodsconstructors and methods • Encapsulation ensures that when fieldsEncapsulation ensures that when fields change, no changes are needed in otherchange, no changes are needed in other classes (a principle known as “locality”)classes (a principle known as “locality”) • Hiding implementation details reducesHiding implementation details reduces complexitycomplexity  easier maintenanceeasier maintenance 33
  • 34. Encapsulation – ExampleEncapsulation – Example • Data Fields are privateData Fields are private • Constructors and accessor methods areConstructors and accessor methods are defineddefined 34
  • 35. PolymorphismPolymorphism • Ability to take more than one formAbility to take more than one form • A class can be used through its parentA class can be used through its parent class's interfaceclass's interface • A subclass may override the implementationA subclass may override the implementation of an operation it inherits from a superclassof an operation it inherits from a superclass (late binding)(late binding) • Polymorphism allows abstract operationsPolymorphism allows abstract operations to be defined and usedto be defined and used • Abstract operations are defined in the baseAbstract operations are defined in the base class's interface and implemented in theclass's interface and implemented in the subclassessubclasses 35
  • 36. 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 sameTo mix different related types in the same collectioncollection • To pass it to a method that expects aTo 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 inTo declare a more generic field (especially in an abstract class) which will be initializedan abstract class) which will be initialized and “specialized” laterand “specialized” later 36
  • 37. Polymorphism – ExamplePolymorphism – Example 37 Square::calcSurface() {Square::calcSurface() { return size * size;return size * size; }} Circle::calcSurface() {Circle::calcSurface() { return PI * radius *return PI * radius * raduis;raduis; }} AbstractAbstract classclass AbstractAbstract classclass AbstractAbstract actionaction AbstractAbstract actionaction ConcreteConcrete classclass ConcreteConcrete classclass OverridenOverriden actionaction OverridenOverriden actionaction OverridenOverriden actionaction OverridenOverriden actionaction
  • 38. PolymorphismPolymorphism • Polymorphism ensures that the appropriatePolymorphism ensures that the appropriate method is called for an object of a specificmethod is called for an object of a specific type when the object is disguised as a moretype 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();
  • 39. Polymorphism in JavaPolymorphism in Java • Good news: polymorphism is alreadyGood 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 aPolymorphism is implemented using a technique calledtechnique called latelate method bindingmethod binding:: • Exact method to call is determined at runExact method to call is determined at run time before performing the calltime before performing the call 39
  • 41. ProblemsProblems 1.1. Describe the termDescribe the term objectobject in OOP.in OOP. 2.2. Describe the termDescribe the term classclass in OOP.in OOP. 3.3. Describe the termDescribe the term interfaceinterface in OOP.in OOP. 4.4. Describe the termDescribe the term inheritanceinheritance in OOP.in OOP. 5.5. Describe the termDescribe the term abstractionabstraction in OOP.in OOP. 6.6. Describe the termDescribe the term encapsulationencapsulation in OOP.in OOP. 7.7. Describe the termDescribe the term polymorphismpolymorphism in OOP.in OOP. 41

Editor's Notes

  1. The industry has embraced OOP, but no formal studies of these claimed benefits have been carried out.