1 data abstraction and object orientation. 2 chapter 9: data abstraction and object orientation 9.1...

44
1 Data Abstraction and Object Data Abstraction and Object Orientation Orientation

Upload: hubert-stevenson

Post on 18-Dec-2015

229 views

Category:

Documents


3 download

TRANSCRIPT

11

Data Abstraction and Object Data Abstraction and Object OrientationOrientation

22

Chapter 9: Data Abstraction and Chapter 9: Data Abstraction and Object OrientationObject Orientation

9.1 Encapsulation and Inheritance

9.2 Initialization and Finalization

9.3 Polymorphism & Dynamic Method Binding

9.4 RTTI and IntrospectionRTTI and Introspection

33

Fundamental Concepts in OOPFundamental Concepts in OOP

• EncapsulationEncapsulation– Data AbstractionData Abstraction– Information hidingInformation hiding– The notion of class and objectThe notion of class and object

• InheritanceInheritance– Code reusabilityCode reusability– Is-a vs. has-a relationshipsIs-a vs. has-a relationships

44

EncapsulationEncapsulation

• Data abstractionData abstraction allow programmers to hide data allow programmers to hide data representation details behind a (comparatively) representation details behind a (comparatively) simple set of operations (an simple set of operations (an interfaceinterface))

• What the benefits of data abstraction?What the benefits of data abstraction?– Reduces Reduces conceptual loadconceptual load

» Programmers need to knows less about the rest of the programProgrammers need to knows less about the rest of the program

– Provides Provides fault containmentfault containment» Bugs are located in independent componentsBugs are located in independent components

– Provides a significant degree of Provides a significant degree of independenceindependence of program of program componentscomponents

» Separate the roles of different programmerSeparate the roles of different programmerSoftware Software

EngineeringEngineeringGoalsGoals

55

EncapsulationEncapsulationClasses, Objects and MethodsClasses, Objects and Methods

• The unit of encapsulation in an O-O PL is a The unit of encapsulation in an O-O PL is a classclass– An abstract data typeAn abstract data type

» The set of values is the set of The set of values is the set of objectsobjects (or (or instancesinstances))

• Objects can have aObjects can have a– Set of Set of instanceinstance attributes attributes ((has-a relationshiphas-a relationship))– Set of Set of instanceinstance methodsmethods

• Classes can have aClasses can have a– Set of Set of class attributesclass attributes– Set of Set of class methodsclass methods

Method calls are Method calls are known as known as messagesmessages

• The entire set of methods of an object is known as the The entire set of methods of an object is known as the message protocolmessage protocol or the or the message interface message interface of the objectof the object

66

EncapsulationEncapsulationModules and ClassesModules and Classes

• The basic unit of OO, the class, is a The basic unit of OO, the class, is a unit of scopeunit of scope– This idea originated in module-based languages in the This idea originated in module-based languages in the

mid-70smid-70s» E.g.E.g. Clu, Modula, Euclid Clu, Modula, Euclid

• Rules of scope enforce data hidingRules of scope enforce data hiding– Names have to be Names have to be exportedexported in order to be accessible by in order to be accessible by

other modulesother modules– What kind of data hiding mechanisms do we have in Java?What kind of data hiding mechanisms do we have in Java?

» http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrohttp://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.htmll.html

– And in Python?And in Python?» http://www.python.org/doc/current/tut/node11.html#SECTION00http://www.python.org/doc/current/tut/node11.html#SECTION00

1160000000000000000011600000000000000000

77

InheritanceInheritance

• Encapsulation improves code reusabilityEncapsulation improves code reusability– Abstract Data TypesAbstract Data Types– ModulesModules– ClassesClasses

• However, it is generally the case that the code a However, it is generally the case that the code a programmer wants to reuse is close but not exactly programmer wants to reuse is close but not exactly what the programmer needswhat the programmer needs

• InheritanceInheritance provides a mechanism to extend or provides a mechanism to extend or refine units of encapsulationrefine units of encapsulation

– By adding or By adding or overridingoverriding methods methods– By adding attributesBy adding attributes

88

InheritanceInheritanceSubtypeSubtype

Java.awt.DialogJava.awt.Dialog

Java.awt.FileDialogJava.awt.FileDialog

Base ClassBase Class

Derived ClassDerived Class

Is-a relationshipIs-a relationship

• The derived class has all the members (The derived class has all the members (i.e.i.e. attributes attributes and methods) of the base classand methods) of the base class

– Any object of the derived class can be used in any context Any object of the derived class can be used in any context that expect an object of the base classthat expect an object of the base class

– fp = new FileDialog() is fp = new FileDialog() is bothboth an object of class Dialog and an object of class Dialog and an object of class File Dialogan object of class File Dialog

99

Chapter 14: Building a runnable Chapter 14: Building a runnable programprogram

9.1 Encapsulation and Inheritance

9.2 Initialization and Finalization

9.3 Polymorphism & Dynamic Method Binding

9.4 RTTI and IntrospectionRTTI and Introspection

1010

Object Lifetime: ConstructorsObject Lifetime: Constructors

• ContructorsContructors are methods used to are methods used to initializeinitialize the the content of an objectcontent of an object

– They do not allocate spaceThey do not allocate space

• Most languages allow multiple constructorsMost languages allow multiple constructors– They are distinguished using different names or different They are distinguished using different names or different

parameters (type and/or number)parameters (type and/or number)– Java and C++ overload the constructor name, so the Java and C++ overload the constructor name, so the

appropriate methods is selected using the number and the appropriate methods is selected using the number and the type of the argumentstype of the arguments» Rectangle r;Rectangle r;» Invokes the parameterless constructorInvokes the parameterless constructor

– Smalltalk and Eiffel support different constructor namesSmalltalk and Eiffel support different constructor names

1111

Constructors in EiffelConstructors in Eiffel

Complex Complex Numbers Numbers

ClassClass

Constructors (!! equals Constructors (!! equals new)new)

Explicit Constructor DeclarationExplicit Constructor Declaration

1212

Constructors in C++Constructors in C++

InitializationInitialization((notnot assignment) assignment)

Copy ConstructorCopy Constructoroperator=operator=

1313

Execution OrderExecution Order

• How is an object of class B derived from class A How is an object of class B derived from class A initialized?initialized?

• In C++ and Java, the constructor of A is invoked In C++ and Java, the constructor of A is invoked before the constructor of Bbefore the constructor of B

– Why?Why?» So the B constructor never sees uninitialized attributesSo the B constructor never sees uninitialized attributes

– What are the arguments of the A constructor?What are the arguments of the A constructor?» In C++, they are explicitly definedIn C++, they are explicitly definedB::B (B_params) : A (A_args) { … }B::B (B_params) : A (A_args) { … }» Futhermore, constructors for object arguments can also be Futhermore, constructors for object arguments can also be

initializedinitializedlist_node() : prev(this), next(this), list_node() : prev(this), next(this), head_node(this), val(0) { }head_node(this), val(0) { }

1414

Java ExampleJava Example

• See Java Language SpecificationSee Java Language Specification– http://java.sun.com/docs/books/jls/second_edition/html/clahttp://java.sun.com/docs/books/jls/second_edition/html/cla

sses.doc.html#41652sses.doc.html#41652– http://java.sun.com/docs/books/jls/second_edition/html/exhttp://java.sun.com/docs/books/jls/second_edition/html/ex

pressions.doc.html#23302pressions.doc.html#23302

1515

Object Lifetime: DestructorsObject Lifetime: Destructors

• DestructorsDestructors are methods used to are methods used to finalizefinalize the content the content of an objectof an object

– They do not deallocate spaceThey do not deallocate space– Language implementations that support automatic garbage Language implementations that support automatic garbage

collection greatly reduce the need for destructorscollection greatly reduce the need for destructors» Most C++ compiler do not support GCMost C++ compiler do not support GC

1616

C++ ExampleC++ Example

• In general, C++ destructors are used for manual In general, C++ destructors are used for manual storage reclamationstorage reclamation

DestructorDestructor

1717

References and ValuesReferences and Values

• Some OO languages use the reference modelSome OO languages use the reference model– Variable refers to objectVariable refers to object– More elegantMore elegant– Extra level of indirection on every accessExtra level of indirection on every access– E.g.E.g. Java, Simula, Smalltalk Java, Simula, Smalltalk

• Other languages use the value modelOther languages use the value model– Allow a variable to have a value that is an objectAllow a variable to have a value that is an object– More efficientMore efficient– More difficult to control initializationMore difficult to control initialization

» E.g. uninitialized objects, mutual referencesE.g. uninitialized objects, mutual references

– E.g.E.g. C++, Ada 95 C++, Ada 95

1818

Chapter 14: Building a runnable Chapter 14: Building a runnable programprogram

9.1 Encapsulation and Inheritance

9.2 Initialization and Finalization

9.3 Polymorphism & Dynamic Method Binding

9.4 RTTI and IntrospectionRTTI and Introspection

1919

PolymorphismPolymorphism

• The is-a relationship supports the development of The is-a relationship supports the development of generic operations that can be applied to objects of a generic operations that can be applied to objects of a class and all its subclassesclass and all its subclasses

– This feature is known as This feature is known as polymorphismpolymorphism– E.g. E.g. paint()paint() method method

• The binding of messages to method definition is The binding of messages to method definition is instance-dependent, and it is known as dynamic instance-dependent, and it is known as dynamic bindingbinding

– It has to be resolved at run-timeIt has to be resolved at run-time– Dynamic binding requires the Dynamic binding requires the virtualvirtual keyword in C++ keyword in C++– Static binding requires the Static binding requires the finalfinal keyword in Java keyword in Java

2020

Method BindingMethod Binding

Classes Student and Professor Classes Student and Professor derive from class Personderive from class Person

Method print_mailing_list Method print_mailing_list is is polymorphicpolymorphic

Results depend on the Results depend on the binding: static or dynamicbinding: static or dynamic

Print_mailing_label redefined for student and professor classesPrint_mailing_label redefined for student and professor classes

2121

Method BindingMethod BindingStatic and DynamicStatic and Dynamic

• In In static method bindingstatic method binding, method selection depends , method selection depends on the type of the variable x and yon the type of the variable x and y

– Method print_mailing_label() of class person is executed Method print_mailing_label() of class person is executed in both casesin both cases

– Resolved at compile timeResolved at compile time

• In In dynamic method bindingdynamic method binding, method selection , method selection depends on the class of the objects s and pdepends on the class of the objects s and p

– Method print_mailing_label() of class student is executed Method print_mailing_label() of class student is executed in the first case, while the corresponding methods for class in the first case, while the corresponding methods for class professor is executed in the second caseprofessor is executed in the second case

– Resolved at run timeResolved at run time

2222

Polymorphism and Dynamic BindingPolymorphism and Dynamic Binding

• The is-a relationship supports the development of The is-a relationship supports the development of generic operationsgeneric operations that can be applied to objects of a that can be applied to objects of a class and all its subclassesclass and all its subclasses

– This feature is known as This feature is known as polymorphismpolymorphism– E.g. E.g. paint()paint() method is polymorphic (accepts multiple method is polymorphic (accepts multiple

types)types)

• The binding of messages to method definitions is The binding of messages to method definitions is instance-dependent, and it is known as dynamic instance-dependent, and it is known as dynamic bindingbinding

– It has to be resolved at run-timeIt has to be resolved at run-time– Dynamic binding requires the Dynamic binding requires the virtualvirtual keyword in C++ keyword in C++– Static binding requires the Static binding requires the finalfinal keyword in Java keyword in Java

2323

Polymorphism examplePolymorphism example

//: Shapes.java//: Shapes.java

package c11;package c11;

import java.util.*;import java.util.*;

interface interface ShapeShape { {

void draw();void draw();

}}

class class CircleCircle implements Shape { implements Shape {

public void draw() {public void draw() {

System.out.println("Circle.draw()");System.out.println("Circle.draw()");

}}

}}

class class SquareSquare implements Shape { implements Shape {

public void draw() {public void draw() {

System.out.println("Square.draw()");System.out.println("Square.draw()");

}}

}}

class class TriangleTriangle implements Shape { implements Shape {

public void draw() {public void draw() {

System.out.println("Triangle.draw()");System.out.println("Triangle.draw()");

}}

}}

public class Shapes {public class Shapes {

public static void main(String[] args) {public static void main(String[] args) {

Vector s = new Vector();Vector s = new Vector();

s.addElement(new Circle());s.addElement(new Circle());

s.addElement(new Square());s.addElement(new Square());

s.addElement(new Triangle());s.addElement(new Triangle());

Enumeration e = s.elements();Enumeration e = s.elements();

while(e.hasMoreElements())while(e.hasMoreElements())

((Shape)e.nextElement()).draw();((Shape)e.nextElement()).draw();

}}

}}

Upcasting (Type Safe in Java)Upcasting (Type Safe in Java)

Poly-Poly-morphismmorphism

2424

Dynamic Binding ImplementationDynamic Binding Implementation

• A common implementation is based on a A common implementation is based on a virtual virtual method tablemethod table (vtable) (vtable)

– Each object keeps a pointer to the vtable that corresponds Each object keeps a pointer to the vtable that corresponds to its classto its class

2525

Dynamic Binding ImplementationDynamic Binding Implementation

• Given an object of class foo, and pointer f to this Given an object of class foo, and pointer f to this object, the code that is used to invoke the appropriate object, the code that is used to invoke the appropriate method would bemethod would be

this (self)this (self)

(polymorphic) method invocation(polymorphic) method invocation

2626

Dynamic Binding ImplementationDynamic Binding ImplementationSimple InheritanceSimple Inheritance

• Derived classes extend the vtable of their base classDerived classes extend the vtable of their base class– Entries of overridden methods contain the address of the Entries of overridden methods contain the address of the

new methodsnew methods

2727

Dynamic Binding ImplementationDynamic Binding ImplementationMultiple InheritanceMultiple Inheritance

• A class may derive from more that one base classA class may derive from more that one base class– This is known as multiple inheritanceThis is known as multiple inheritance

• Multiple inheritance is also implemented using Multiple inheritance is also implemented using vtablesvtables

– Two casesTwo cases» Non-repeated multiple inheritanceNon-repeated multiple inheritance» Repeated multiple inheritanceRepeated multiple inheritance

2828

Dynamic Method BindingDynamic Method BindingNon-Repeated Multiple InheritanceNon-Repeated Multiple Inheritance

2929

Dynamic Method BindingDynamic Method BindingNon-Repeated Multiple InheritanceNon-Repeated Multiple Inheritance

• The view of this must be corrected, so it points to the The view of this must be corrected, so it points to the correct part of the objectscorrect part of the objects

– An offset An offset dd is use to locate the appropriate vtable pointer is use to locate the appropriate vtable pointer» d d is known at compile timeis known at compile time

this this (self)(self)

3030

Dynamic Method BindingDynamic Method BindingRepeated Multiple InheritanceRepeated Multiple Inheritance

• Multiple inheritance introduces a semantic problem: Multiple inheritance introduces a semantic problem: method name collisionsmethod name collisions

– Ambiguous method namesAmbiguous method names– Some languages support inherited method renaming (Some languages support inherited method renaming (e.g.e.g.

Eiffel)Eiffel)– Other languages, like C++, require a reimplementation that Other languages, like C++, require a reimplementation that

solves the ambiguitysolves the ambiguity– Java Java solvessolves the problem by not supporting multiple the problem by not supporting multiple

inheritanceinheritance» A class may inherit multiple interfaces, but, in the absence of A class may inherit multiple interfaces, but, in the absence of

implementations, the collision is irrelevantimplementations, the collision is irrelevant

3131

Chapter 14: Building a runnable Chapter 14: Building a runnable programprogram

9.1 Encapsulation and Inheritance

9.2 Initialization and Finalization

9.3 Polymorphism & Dynamic Method Binding

9.4 RTTI and IntrospectionRTTI and Introspection

3232

• 1. public class Base { 1. public class Base { • 2. } 2. } • 3. public class Derived extends Base { 3. public class Derived extends Base { • 4. } 4. } • 5. 5. • 6. // Test the getClass() method for the above classes. 6. // Test the getClass() method for the above classes. • 7. Base base = new Base(); 7. Base base = new Base(); • 8. Base derived = new Derived(); 8. Base derived = new Derived(); • 9. 9. • 10. System.out.println("Class for base object = " + 10. System.out.println("Class for base object = " + • 11. 11. base.getClass().toString()); base.getClass().toString()); • 12. System.out.println("Class for derived object = " + 12. System.out.println("Class for derived object = " + • 13. 13. derived.getClass().toString()); derived.getClass().toString());

3333

RTTI and IntrospectionRTTI and Introspection

• Run-time type identificationRun-time type identification make it possible to make it possible to determine the type of an object determine the type of an object

– E.g. given a pointer to a base class, determine the derived E.g. given a pointer to a base class, determine the derived class of the pointed objectclass of the pointed object

– The type (class) must be known at compile timeThe type (class) must be known at compile time

• IntrospectionIntrospection makes general class information makes general class information available at run-timeavailable at run-time

– The type (class) does not have to be known at compile The type (class) does not have to be known at compile timetime

– This is very useful in component architectures and visual This is very useful in component architectures and visual programmingprogramming

– E.g. list the attributes of an objectE.g. list the attributes of an object

3434

RTTI and IntrospectionRTTI and Introspection

• RTTI and introspection are powerful programming RTTI and introspection are powerful programming language featureslanguage features

– They enables some powerful design techniquesThey enables some powerful design techniques– We will discuss them in the context of JavaWe will discuss them in the context of Java

• This discussion will follow Chapter 12 in This discussion will follow Chapter 12 in Thinking in Thinking in JavaJava by Bruce Eckel by Bruce Eckel

– http://www.codeguru.com/java/tij/tij0119.shtmlhttp://www.codeguru.com/java/tij/tij0119.shtml– By the way, this is an excellent book freely available on-By the way, this is an excellent book freely available on-

lineline

3535

The need for RTTIThe need for RTTIPolymorphism ExamplePolymorphism Example

//: Shapes.java//: Shapes.java

package c11;package c11;

import java.util.*;import java.util.*;

interface interface ShapeShape { {

void draw();void draw();

}}

class class CircleCircle implements Shape { implements Shape {

public void draw() {public void draw() {

System.out.println("Circle.draw()");System.out.println("Circle.draw()");

}}

}}

class class SquareSquare implements Shape { implements Shape {

public void draw() {public void draw() {

System.out.println("Square.draw()");System.out.println("Square.draw()");

}}

}}

class class TriangleTriangle implements Shape { implements Shape {

public void draw() {public void draw() {

System.out.println("Triangle.draw()");System.out.println("Triangle.draw()");

}}

}}

public class Shapes {public class Shapes {

public static void main(String[] args) {public static void main(String[] args) {

Vector s = new Vector();Vector s = new Vector();

s.addElement(new Circle());s.addElement(new Circle());

s.addElement(new Square());s.addElement(new Square());

s.addElement(new Triangle());s.addElement(new Triangle());

Enumeration e = s.elements();Enumeration e = s.elements();

while(e.hasMoreElements())while(e.hasMoreElements())

((Shape)e.nextElement()).draw();((Shape)e.nextElement()).draw();

}}

}}

Upcasting (Type Safe in Java)Upcasting (Type Safe in Java)

Poly-Poly-morphismmorphism

What if you want to known the exact type at run-time?What if you want to known the exact type at run-time?

3636

The Class ObjectThe Class Object

• Type information is available at run-time in JavaType information is available at run-time in Java

• There is a There is a Class objectClass object for each class in the program for each class in the program– It stores class informationIt stores class information

• Class objects are loaded in memory the first time Class objects are loaded in memory the first time they are needed by finding the .class file with that they are needed by finding the .class file with that namename

– The static initialization is performed upon class loadingThe static initialization is performed upon class loading– A Java program is not completely loaded before it begin!A Java program is not completely loaded before it begin!

• The class The class ClassClass provides a number of useful provides a number of useful methods for RTTImethods for RTTI

– http://java.sun.com/j2se/1.3/docs/api/java/lang/Class.htmlhttp://java.sun.com/j2se/1.3/docs/api/java/lang/Class.html

3737

ExampleExample

classclass Candy { Candy {

staticstatic { {

System.out.println("Loading Candy"); System.out.println("Loading Candy");

} }

} }

classclass Gum { Gum {

staticstatic { {

System.out.println("Loading Gum"); System.out.println("Loading Gum");

} }

} }

classclass Cookie { Cookie {

staticstatic { {

System.out.println("Loading System.out.println("Loading Cookie"); Cookie");

} }

} }

publicpublic classclass SweetShop { SweetShop {

publicpublic staticstatic voidvoid main(String[] args) { main(String[] args) {

System.out.println("inside main");System.out.println("inside main");

newnew Candy(); Candy();

System.out.println("After creating System.out.println("After creating Candy"); Candy");

trytry { {

Class.forName("Gum"); Class.forName("Gum");

} } catchcatch(ClassNotFoundException e) {(ClassNotFoundException e) {

e.printStackTrace(); e.printStackTrace();

} }

System.out.println( "After System.out.println( "After Class.forName(\"Gum\")"); Class.forName(\"Gum\")");

newnew Cookie(); Cookie();

System.out.println("After creating System.out.println("After creating Cookie"); Cookie");

} }

} }

Executed at Load TimeExecuted at Load Time

Returns a reference to class GumReturns a reference to class Gum

3838

ExampleExample

• OutputOutput– JVM-1JVM-1

inside main inside main Loading Candy Loading Candy After creating Candy After creating Candy Loading Gum Loading Gum After Class.forName("Gum") After Class.forName("Gum") Loading Cookie Loading Cookie After creating Cookie After creating Cookie

3939

ExampleExample

• OutputOutput– JVM-2JVM-2

Loading Candy Loading Candy Loading Cookie Loading Cookie inside main inside main After creating Candy After creating Candy Loading Gum Loading Gum After Class.forName("Gum") After Class.forName("Gum") After creating Cookie After creating Cookie

4040

The Class ObjectThe Class Object

• Class literals also provide a reference to the Class Class literals also provide a reference to the Class objectobject

– E.g.E.g. Gum.classGum.class

• Each object of a primitive wrapper class has a Each object of a primitive wrapper class has a standard field called TYPE that also provides a standard field called TYPE that also provides a reference to the Class objectreference to the Class object

– http://java.sun.com/j2se/1.3/docs/api/java/lang/Boolean.hthttp://java.sun.com/j2se/1.3/docs/api/java/lang/Boolean.htmlml

4141

RTTIRTTI

• The type of a object can be determined using the The type of a object can be determined using the instanceofinstanceof keyword keyword

– an operator, not a function an operator, not a function – Notice that an object of a derived class is an instance of Notice that an object of a derived class is an instance of

the its base classes (the its base classes (i.e.i.e. any predecessor in the inheritance any predecessor in the inheritance hierarchy)hierarchy)

• RTTI is very useful when reusing classes without RTTI is very useful when reusing classes without extending themextending them

• Class.isInstance()Class.isInstance() also implements the also implements the instanceofinstanceof functionality functionality

– if ( Class.forName ( classNameString ).isInstance if ( Class.forName ( classNameString ).isInstance ( myObject ) ) …( myObject ) ) …

4242

IntrospectionIntrospection

• IntrospectionIntrospection makes general class information makes general class information available at run-timeavailable at run-time

– The type (class) does not have to be known at compile The type (class) does not have to be known at compile timetime

– E.g. list the attributes of an objectE.g. list the attributes of an object

• This is very useful in This is very useful in – Rapid Application Development (RAD)Rapid Application Development (RAD)

» Visual approach to GUI developmentVisual approach to GUI development» Requires information about component at run-timeRequires information about component at run-time

– Remote Method Invocation (RMI)Remote Method Invocation (RMI)» Distributed objectsDistributed objects

4343

ReflectionReflection

• Java supports introspection through its reflection Java supports introspection through its reflection librarylibrary

– http://java.sun.com/j2se/1.3/docs/api/java/lang/reflect/packhttp://java.sun.com/j2se/1.3/docs/api/java/lang/reflect/package-summary.htmlage-summary.html

– See classes Field (attributes), Method and ConstructorSee classes Field (attributes), Method and Constructor

• Examples:Examples:– ShowMethods.javaShowMethods.java

4444

PythonPython

• The Inspect module provides introspections The Inspect module provides introspections mechanismmechanism

– http://www.python.org/doc/current/lib/module-inspect.htmhttp://www.python.org/doc/current/lib/module-inspect.htmll

– See:See:» getmembers(object[, predicate])getmembers(object[, predicate])» getsource(object) getsource(object) » getclasstree(classes[, unique])getclasstree(classes[, unique])» getmro(cls)getmro(cls)