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
 
Introduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingIntroduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingMoutaz Haddara
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Michelle Anne Meralpis
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
Basic concepts of object oriented programming
Basic concepts of object oriented programmingBasic concepts of object oriented programming
Basic concepts of object oriented programmingSachin Sharma
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Sanjit Shaw
 
WHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAWHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAsivasundari6
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented ProgrammingIqra khalil
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 
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
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in javaNilesh Dalvi
 
Principles and advantages of oop ppt
Principles and advantages of oop pptPrinciples and advantages of oop ppt
Principles and advantages of oop pptdaxesh chauhan
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++HalaiHansaika
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functionsHarsh Patel
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principlesdeonpmeyer
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator OverloadingNilesh Dalvi
 

What's hot (20)

Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Object Oriented Design
Object Oriented DesignObject Oriented Design
Object Oriented Design
 
Introduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingIntroduction to Object Oriented Programming
Introduction to Object Oriented Programming
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Basic concepts of object oriented programming
Basic concepts of object oriented programmingBasic concepts of object oriented programming
Basic concepts of object oriented programming
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)
 
WHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAWHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVA
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming language
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Principles and advantages of oop ppt
Principles and advantages of oop pptPrinciples and advantages of oop ppt
Principles and advantages of oop ppt
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functions
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principles
 
Polymorphism in oop
Polymorphism in oopPolymorphism in oop
Polymorphism in oop
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 

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

fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 

Recently uploaded (20)

fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 

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.