object orientation yaodong bi, ph.d. department of computer sciences university of scranton...
TRANSCRIPT
Object OrientationObject Orientation
Yaodong Bi, Ph.D.Yaodong Bi, Ph.D.Department of Computer SciencesDepartment of Computer SciencesUniversity of ScrantonUniversity of Scranton
April 19, 2023April 19, 2023
Classes and objects for Classes and objects for modelingmodeling
ClassesClasses– Real world conceptsReal world concepts– Student, course, bicycle, etcStudent, course, bicycle, etc
ObjectsObjects– Instances of real word conceptsInstances of real word concepts– John Smith, Operating Systems, John Smith, Operating Systems,
Mongoose Mountain S100, etcMongoose Mountain S100, etc
04/19/2304/19/23 22
Classes and objects for Classes and objects for modelingmodeling
“Customers John and
Susan entered the MakeMoney
bank and were served by
teller Andy.”
Classes
Objects:
04/19/2304/19/23 33
Classes and objects in Classes and objects in softwaresoftware
ObjectsObjects– Packaging both data and the procedures that Packaging both data and the procedures that
operate on the data into oneoperate on the data into one– Operations are the only way to change the data Operations are the only way to change the data
items – items – encapsulationencapsulation ClassesClasses
– Template of objects of the same typeTemplate of objects of the same type– Write once and use many timesWrite once and use many times
Implementation classes/objectsImplementation classes/objects– Some classes/objects do not match to concepts in Some classes/objects do not match to concepts in
the real worldthe real world List, stack, tree, queue – containersList, stack, tree, queue – containers Exception classesException classes
04/19/2304/19/23 44
Attributes and operationsAttributes and operations
Instance attributes (simply attributes)Instance attributes (simply attributes)– Properties (internal state) of an objectProperties (internal state) of an object
Student: name, major, class, GPAStudent: name, major, class, GPA Course: title, # of credits, descriptionCourse: title, # of credits, description
– Each object has its own value for an Each object has its own value for an attributeattribute
Instance operations (simply operations)Instance operations (simply operations)– Services of an objectServices of an object
Stack: push, pop, isEmpty, isFullStack: push, pop, isEmpty, isFull– EncapsulationEncapsulation
Attributes (private and protected) are not Attributes (private and protected) are not accessible directly by clientaccessible directly by client
Operations are used to read/write the values of Operations are used to read/write the values of attributesattributes04/19/2304/19/23 55
Attributes and OperationsAttributes and Operations
Class attributes (static attributes)Class attributes (static attributes)– Represent properties that can be applied Represent properties that can be applied
to all objects of the same classto all objects of the same class– Only one value for each class attribute Only one value for each class attribute
shared by all objects of the classshared by all objects of the class All accounts of the All accounts of the CheckingAccountCheckingAccount class have class have
the same interest ratethe same interest rate– Can be accessed in both instance and Can be accessed in both instance and
class operationsclass operations Class operations (static operations)Class operations (static operations)
– Used to access class attributesUsed to access class attributes– Cannot access instance attributes and Cannot access instance attributes and
operationsoperations04/19/2304/19/23 66
Class member access modesClass member access modes
PublicPublic– Public attributes and public operationsPublic attributes and public operations– Accessible to all clients or the worldAccessible to all clients or the world
ProtectedProtected– Protected attributes and operationsProtected attributes and operations– Accessible to the class and its subclasses Accessible to the class and its subclasses
PrivatePrivate– Private attributes and operationsPrivate attributes and operations– Only accessible by the operations of the Only accessible by the operations of the
classclass04/19/2304/19/23 77
Member access modes in Member access modes in JavaJava
SpecifierSpecifier ClassClass PackagePackage SubclassSubclass WorldWorld
PrivatePrivate YY NN NN NN
No No SpecifierSpecifier
YY YY NN NN
ProtectedProtected YY YY YY NN
PublicPublic YY YY YY YY
04/19/2304/19/23 88
Abstract and concrete Abstract and concrete classesclasses
Abstract classesAbstract classes– Define a common interface for its Define a common interface for its
subclassessubclasses– Defer some or all of its implementation of Defer some or all of its implementation of
operations to its subclassesoperations to its subclasses– Cannot be instantiatedCannot be instantiated
Concrete classesConcrete classes– That are not abstract classesThat are not abstract classes– Can be instantiatedCan be instantiated– Concrete subclasses implement all the Concrete subclasses implement all the
operationsoperations04/19/2304/19/23 99
InterfacesInterfaces
Signature of an operation:Signature of an operation:– Operation nameOperation name– Objects/classes it takes as parametersObjects/classes it takes as parameters– Return value and typeReturn value and type
Interface:Interface:– The set of signatures of related operationsThe set of signatures of related operations– Representing a capability or a set of Representing a capability or a set of
servicesservices– A class may implement multiple interfacesA class may implement multiple interfaces
Its objects have more than one set of servicesIts objects have more than one set of services04/19/2304/19/23 1010
InheritanceInheritance
Specifies Specifies is-ais-a or or a-kind-ofa-kind-of relationshiprelationship
Generalization and specializationGeneralization and specialization Superclasses and subclassesSuperclasses and subclasses Single and multiple inheritanceSingle and multiple inheritance Class and interface inheritanceClass and interface inheritance
04/19/2304/19/23 1111
Superclasses and Superclasses and subclassessubclasses
SuperclassSuperclass– Also called base class or parent classAlso called base class or parent class– All of its members are inherited by All of its members are inherited by
its subclasses its subclasses SubclassesSubclasses
– Also called child classesAlso called child classes– Inherit all the properties of its Inherit all the properties of its
superclassessuperclasses04/19/2304/19/23 1212
Single and multiple Single and multiple inheritanceinheritance
Single inheritanceSingle inheritance– A subclass cannot have more than one A subclass cannot have more than one
parent parent Multiple inheritanceMultiple inheritance
– A subclass may have more than one A subclass may have more than one parentparent
– Java does not allow multiple inheritanceJava does not allow multiple inheritance– Java allows multiple interface Java allows multiple interface
inheritanceinheritance Through interface implementationThrough interface implementation
04/19/2304/19/23 1313
Class inheritance latticeClass inheritance lattice
PersonSSN
NamegetSSN()
getName()
Facultyoffice
getOffice()Staffdept
getDept()
Studentmajor
getMajor()
FullTime
salarygetSalary()
PartTime
PayRategetPayRate(
)
Graduate
PayRategetPayRate(
)
UndergPayRate
getPayRate()
TAlabs
getLabs()04/19/2304/19/23 1414
Implementation inheritanceImplementation inheritance
Also called class inheritanceAlso called class inheritance Define an object’s Define an object’s
implementation in terms of implementation in terms of another object’s implementationanother object’s implementation
Pure class inheritance in C++Pure class inheritance in C++ Pure class inheritance in JavaPure class inheritance in Java
04/19/2304/19/23 1515
Pure class inheritance with Pure class inheritance with C++C++
Class BinaryTree {Class BinaryTree {
getRoot() {;}getRoot() {;}
setRoot() {;}setRoot() {;}
leftTree() {;}leftTree() {;}
rightTree() {;}rightTree() {;}
}}
Class BinSearchTree: Class BinSearchTree: privateprivate BinaryTree BinaryTree
{{
insert() {;}insert() {;}
remove() {;}remove() {;}
find() {;}find() {;}
}}
They use the operations of BinaryTree
The operations of BinaryTree are not
accessible/visible to the clients of BinSearchTree because BinaryTree is
private04/19/2304/19/23 1616
Pure class inheritance with Pure class inheritance with JavaJava
Java does not allow private parentJava does not allow private parent The parent and grandparents are The parent and grandparents are
public and accessible through the public and accessible through the subclasssubclass
Java cannot implement pure Java cannot implement pure implementation inheritance.implementation inheritance.
04/19/2304/19/23 1717
Interface inheritanceInterface inheritance
Describe when an object can be Describe when an object can be used in place of anotherused in place of another
Pure interface inheritance in C++Pure interface inheritance in C++– Superclasses are pure abstract Superclasses are pure abstract
classesclasses Pure interface inheritance in JavaPure interface inheritance in Java
– Superclasses are Java interfacesSuperclasses are Java interfaces
04/19/2304/19/23 1818
Interface inheritance with C+Interface inheritance with C+++
Class Stack {Class Stack {virtual push() = 0;virtual push() = 0;virtual pop() = 0;virtual pop() = 0;virtual isEmpty() = 0;virtual isEmpty() = 0;virtual isFull() = 0;virtual isFull() = 0;
}}
Class MyStack: Class MyStack: publicpublic Stack Stack{{
push() {;}push() {;}pop() {;}pop() {;}isEmpty() {;}isEmpty() {;}isFull() {;}isFull() {;}
}}
Class YourStack: Class YourStack: publicpublic Stack Stack{{
push() {;}push() {;}pop() {;}pop() {;}isEmpty() {;}isEmpty() {;}isFull() {;}isFull() {;}
}}
A C++ Abstract class
04/19/2304/19/23 1919
Interface inheritance with Interface inheritance with JavaJava
Interface Stack {Interface Stack {push();push();pop();pop();isEmpty();isEmpty();isFull() 0;isFull() 0;
}}
Class MyStack Class MyStack implements Stack {implements Stack {push() {;}push() {;}pop() {;}pop() {;}isEmpty() {;}isEmpty() {;}isFull() {;}isFull() {;}
}}
Class YourStackClass YourStack
implements Stack {implements Stack {push() {;}push() {;}pop() {;}pop() {;}isEmpty() {;}isEmpty() {;}isFull() {;}isFull() {;}
}}
A Java Interface
04/19/2304/19/23 2020
PolymorphismPolymorphism
When a client sends a request to a When a client sends a request to a reference, the method executed depends reference, the method executed depends on the object behind the referenceon the object behind the reference
Polymorphism and inheritance are very Polymorphism and inheritance are very powerful tool in software design powerful tool in software design
So powerful that if they are used So powerful that if they are used properly, they can hurt really badproperly, they can hurt really bad– If something goes wrong, it is hard to tell If something goes wrong, it is hard to tell
which class/object caused the problemwhich class/object caused the problem
04/19/2304/19/23 2121
Dynamic (late) bindingDynamic (late) binding
Dynamic binding is a way of implementing Dynamic binding is a way of implementing polymorphismpolymorphism
It means that a function call is not linked to It means that a function call is not linked to the actual function until execution timethe actual function until execution time
Since a reference may be used to point to Since a reference may be used to point to different types (subtypes or subclasses) of different types (subtypes or subclasses) of objects at execution time, so the actual objects at execution time, so the actual function to be executed may not be known function to be executed may not be known when the program is compiled. when the program is compiled.
The opposite of dynamic binding is static The opposite of dynamic binding is static binding which links a function call to the binding which links a function call to the actual function at compilation time.actual function at compilation time.
04/19/2304/19/23 2222
Method OverridingMethod Overriding
A subclass overrides the operation(s) A subclass overrides the operation(s) defined in the parent/grandparent classes. defined in the parent/grandparent classes.
This is for specialized subclasses to This is for specialized subclasses to override the behavior defined in the super override the behavior defined in the super class(es).class(es).
For example:For example:– Superclass Employee’s Superclass Employee’s printprint method prints method prints
employee’s SSN, Name, Address.employee’s SSN, Name, Address.– Its subclass Engineer’s Its subclass Engineer’s printprint method prints method prints
engineer’s type and level in addition to engineer’s type and level in addition to employee’s normal information.employee’s normal information.
04/19/2304/19/23 2323
Function overloadingFunction overloading
The same name is used for more than The same name is used for more than functionfunction
For example, a function of adding two For example, a function of adding two integers may be named the same as the integers may be named the same as the one of adding two floats:one of adding two floats:– Add(int x, int y);Add(int x, int y);– Add(float x, float y);Add(float x, float y);– Two functions use the same name for the Two functions use the same name for the
same purpose with different data same purpose with different data parametersparameters
04/19/2304/19/23 2424
Inheritance vs. CompositionInheritance vs. Composition
Two common techniques for reuseTwo common techniques for reuse Class Inheritance Class Inheritance
– White-box reuseWhite-box reuse– Defined at compile-time, staticallyDefined at compile-time, statically– Cannot change parent at rum-timeCannot change parent at rum-time
Object CompositionObject Composition– Black-box reuseBlack-box reuse– A reference/pointer to the objectA reference/pointer to the object– Can be changed at run-timeCan be changed at run-time
Favor composition over inheritanceFavor composition over inheritance04/19/2304/19/23 2525
DelegationDelegation
A way to make composition as A way to make composition as powerful as class inheritancepowerful as class inheritance
A A receiving objectreceiving object delegates delegates requests to its requests to its delegatesdelegates== subclass defers request to parent class== subclass defers request to parent class
In class inheritance In class inheritance – parent can use parent can use thisthis to access the child to access the child
In delegationIn delegation– Receiving object can pass itself to its Receiving object can pass itself to its
delegatedelegate04/19/2304/19/23 2626
Three techniques for reuseThree techniques for reuse
Class InheritanceClass Inheritance– can provide default operations and let subclass can provide default operations and let subclass
override themoverride them– Cannot be changed at run-timeCannot be changed at run-time
Object CompositionObject Composition– Can change the behavior being composed at run-Can change the behavior being composed at run-
timetime– Requires redirection and so becomes less efficientRequires redirection and so becomes less efficient
Generics Generics – Changes the types that a class can useChanges the types that a class can use– Cannot change at run-timeCannot change at run-time
04/19/2304/19/23 2727
ToolkitsToolkits
A set of predefined classes A set of predefined classes Provides useful, general-purpose Provides useful, general-purpose
functionalityfunctionality– Collection classes (list, stack, etc)Collection classes (list, stack, etc)– GWT (Google Web Toolkit)GWT (Google Web Toolkit)
Does NOT impose any design level Does NOT impose any design level decisiondecision
Code ReuseCode Reuse04/19/2304/19/23 2828
FrameworksFrameworks
A reusable design for a type of A reusable design for a type of applicationsapplications
Dictates the architecture of your appDictates the architecture of your app– Overall structureOverall structure– Key components and their responsibilitiesKey components and their responsibilities– How classes/objects interact with each otherHow classes/objects interact with each other
Design reuseDesign reuse Inversion of Control Inversion of Control
– Dependency InjectionDependency Injection
04/19/2304/19/23 2929
FrameworksFrameworks
Framework examples:Framework examples:– Web AppsWeb Apps
J2EE, Spring Framework, .NetJ2EE, Spring Framework, .Net
– ORM (object to relation mapping)ORM (object to relation mapping) Hibernate, OpenJPA, MyBatisHibernate, OpenJPA, MyBatis
– Mobile AppsMobile Apps AndroidAndroid iOSiOS
04/19/2304/19/23 3030