Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Data Abstraction and Object Orientation. 2 Chapter 9: Data Abstraction and Object Orientation 9.1 Encapsulation and Inheritance 9.2 Initialization and.

Similar presentations


Presentation on theme: "1 Data Abstraction and Object Orientation. 2 Chapter 9: Data Abstraction and Object Orientation 9.1 Encapsulation and Inheritance 9.2 Initialization and."— Presentation transcript:

1 1 Data Abstraction and Object Orientation

2 2 Chapter 9: Data Abstraction and Object Orientation 9.1 Encapsulation and Inheritance 9.2 Initialization and Finalization 9.3 Polymorphism & Dynamic Method Binding RTTI and Introspection 9.4 RTTI and Introspection

3 3 Fundamental Concepts in OOP EncapsulationEncapsulation –Data Abstraction –Information hiding –The notion of class and object InheritanceInheritance –Code reusability –Is-a vs. has-a relationships

4 4 Encapsulation Data abstraction allow programmers to hide data representation details behind a (comparatively) simple set of operations (an interface)Data abstraction allow programmers to hide data representation details behind a (comparatively) simple set of operations (an interface) What the benefits of data abstraction?What the benefits of data abstraction? –Reduces conceptual load »Programmers need to knows less about the rest of the program –Provides fault containment »Bugs are located in independent components –Provides a significant degree of independence of program components »Separate the roles of different programmer SoftwareEngineeringGoals

5 5 Encapsulation Classes, Objects and Methods The unit of encapsulation in an O-O PL is a classThe unit of encapsulation in an O-O PL is a class –An abstract data type »The set of values is the set of objects (or instances) Objects can have aObjects can have a –Set of instance attributes (has-a relationship) –Set of instance methods Classes can have aClasses can have a –Set of class attributes –Set of class methods Method calls are known as messages The entire set of methods of an object is known as the message protocol or the message interface of the objectThe entire set of methods of an object is known as the message protocol or the message interface of the object

6 6 Encapsulation Modules and Classes The basic unit of OO, the class, is a unit of scopeThe basic unit of OO, the class, is a unit of scope –This idea originated in module-based languages in the mid-70s »E.g. Clu, Modula, Euclid Rules of scope enforce data hidingRules of scope enforce data hiding –Names have to be exported in order to be accessible by other modules –What kind of data hiding mechanisms do we have in Java? »http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.htmlhttp://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html –And in Python? »http://www.python.org/doc/current/tut/node11.html#SECTION00 11600000000000000000 http://www.python.org/doc/current/tut/node11.html#SECTION00 11600000000000000000http://www.python.org/doc/current/tut/node11.html#SECTION00 11600000000000000000

7 7 Inheritance Encapsulation improves code reusabilityEncapsulation improves code reusability –Abstract Data Types –Modules –Classes However, it is generally the case that the code a programmer wants to reuse is close but not exactly what the programmer needsHowever, it is generally the case that the code a programmer wants to reuse is close but not exactly what the programmer needs Inheritance provides a mechanism to extend or refine units of encapsulationInheritance provides a mechanism to extend or refine units of encapsulation –By adding or overriding methods –By adding attributes

8 8 Inheritance Subtype Java.awt.Dialog Java.awt.FileDialog Base Class Derived Class Is-a relationship The derived class has all the members (i.e. attributes and methods) of the base classThe derived class has all the members (i.e. attributes and methods) of the base class –Any object of the derived class can be used in any context that expect an object of the base class –fp = new FileDialog() is both an object of class Dialog and an object of class File Dialog

9 9 Chapter 14: Building a runnable program 9.1 Encapsulation and Inheritance 9.2 Initialization and Finalization 9.3 Polymorphism & Dynamic Method Binding RTTI and Introspection 9.4 RTTI and Introspection

10 10 Object Lifetime: Constructors Contructors are methods used to initialize the content of an objectContructors are methods used to initialize the content of an object –They do not allocate space Most languages allow multiple constructorsMost languages allow multiple constructors –They are distinguished using different names or different parameters (type and/or number) –Java and C++ overload the constructor name, so the appropriate methods is selected using the number and the type of the arguments »Rectangle r; »Invokes the parameterless constructor –Smalltalk and Eiffel support different constructor names

11 11 Constructors in Eiffel ComplexNumbersClass Constructors (!! equals new) Explicit Constructor Declaration

12 12 Constructors in C++ Initialization (not assignment) Copy Constructor operator=

13 13 Execution Order How is an object of class B derived from class A initialized?How is an object of class B derived from class A initialized? In C++ and Java, the constructor of A is invoked before the constructor of BIn C++ and Java, the constructor of A is invoked before the constructor of B –Why? »So the B constructor never sees uninitialized attributes –What are the arguments of the A constructor? »In C++, they are explicitly defined B::B (B_params) : A (A_args) { … } »Futhermore, constructors for object arguments can also be initialized list_node() : prev(this), next(this), head_node(this), val(0) { }

14 14 Java Example See Java Language SpecificationSee Java Language Specification –http://java.sun.com/docs/books/jls/second_edition/html/cla sses.doc.html#41652 http://java.sun.com/docs/books/jls/second_edition/html/cla sses.doc.html#41652http://java.sun.com/docs/books/jls/second_edition/html/cla sses.doc.html#41652 –http://java.sun.com/docs/books/jls/second_edition/html/ex pressions.doc.html#23302 http://java.sun.com/docs/books/jls/second_edition/html/ex pressions.doc.html#23302http://java.sun.com/docs/books/jls/second_edition/html/ex pressions.doc.html#23302

15 15 Object Lifetime: Destructors Destructors are methods used to finalize the content of an objectDestructors are methods used to finalize the content of an object –They do not deallocate space –Language implementations that support automatic garbage collection greatly reduce the need for destructors »Most C++ compiler do not support GC

16 16 C++ Example In general, C++ destructors are used for manual storage reclamationIn general, C++ destructors are used for manual storage reclamationDestructor

17 17 References and Values Some OO languages use the reference modelSome OO languages use the reference model –Variable refers to object –More elegant –Extra level of indirection on every access –E.g. Java, Simula, Smalltalk Other languages use the value modelOther languages use the value model –Allow a variable to have a value that is an object –More efficient –More difficult to control initialization »E.g. uninitialized objects, mutual references –E.g. C++, Ada 95

18 18 Chapter 14: Building a runnable program 9.1 Encapsulation and Inheritance 9.2 Initialization and Finalization 9.3 Polymorphism & Dynamic Method Binding RTTI and Introspection 9.4 RTTI and Introspection

19 19 Polymorphism The is-a relationship supports the development of generic operations that can be applied to objects of a class and all its subclassesThe is-a relationship supports the development of generic operations that can be applied to objects of a class and all its subclasses –This feature is known as polymorphism –E.g. paint() method The binding of messages to method definition is instance-dependent, and it is known as dynamic bindingThe binding of messages to method definition is instance-dependent, and it is known as dynamic binding –It has to be resolved at run-time –Dynamic binding requires the virtual keyword in C++ –Static binding requires the final keyword in Java

20 20 Method Binding Classes Student and Professor derive from class Person Method print_mailing_list is polymorphic Results depend on the binding: static or dynamic Print_mailing_label redefined for student and professor classes

21 21 Method Binding Static and Dynamic In static method binding, method selection depends on the type of the variable x and yIn static method binding, method selection depends on the type of the variable x and y –Method print_mailing_label() of class person is executed in both cases –Resolved at compile time In dynamic method binding, method selection depends on the class of the objects s and pIn dynamic method binding, method selection depends on the class of the objects s and p –Method print_mailing_label() of class student is executed in the first case, while the corresponding methods for class professor is executed in the second case –Resolved at run time

22 22 Polymorphism and Dynamic Binding The is-a relationship supports the development of generic operations that can be applied to objects of a class and all its subclassesThe is-a relationship supports the development of generic operations that can be applied to objects of a class and all its subclasses –This feature is known as polymorphism –E.g. paint() method is polymorphic (accepts multiple types) The binding of messages to method definitions is instance-dependent, and it is known as dynamic bindingThe binding of messages to method definitions is instance-dependent, and it is known as dynamic binding –It has to be resolved at run-time –Dynamic binding requires the virtual keyword in C++ –Static binding requires the final keyword in Java

23 23 Polymorphism example //: Shapes.java package c11; import java.util.*; interface Shape { void draw(); void draw();} class Circle implements Shape { public void draw() { public void draw() { System.out.println("Circle.draw()"); System.out.println("Circle.draw()"); }} class Square implements Shape { public void draw() { public void draw() { System.out.println("Square.draw()"); System.out.println("Square.draw()"); }} class Triangle implements Shape { public void draw() { public void draw() { System.out.println("Triangle.draw()"); System.out.println("Triangle.draw()"); }} 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) Poly- morphism

24 24 Dynamic Binding Implementation A common implementation is based on a virtual method table (vtable)A common implementation is based on a virtual method table (vtable) –Each object keeps a pointer to the vtable that corresponds to its class

25 25 Dynamic Binding Implementation Given an object of class foo, and pointer f to this object, the code that is used to invoke the appropriate method would beGiven an object of class foo, and pointer f to this object, the code that is used to invoke the appropriate method would be this (self) (polymorphic) method invocation

26 26 Dynamic Binding Implementation Simple 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 new methods

27 27 Dynamic Binding Implementation Multiple 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 inheritance Multiple inheritance is also implemented using vtablesMultiple inheritance is also implemented using vtables –Two cases »Non-repeated multiple inheritance »Repeated multiple inheritance

28 28 Dynamic Method Binding Non-Repeated Multiple Inheritance

29 29 The view of this must be corrected, so it points to the correct part of the objectsThe view of this must be corrected, so it points to the correct part of the objects –An offset d is use to locate the appropriate vtable pointer »d is known at compile time this(self)

30 30 Dynamic Method Binding Repeated Multiple Inheritance Multiple inheritance introduces a semantic problem: method name collisionsMultiple inheritance introduces a semantic problem: method name collisions –Ambiguous method names –Some languages support inherited method renaming (e.g. Eiffel) –Other languages, like C++, require a reimplementation that solves the ambiguity –Java solves the problem by not supporting multiple inheritance »A class may inherit multiple interfaces, but, in the absence of implementations, the collision is irrelevant

31 31 Chapter 14: Building a runnable program 9.1 Encapsulation and Inheritance 9.2 Initialization and Finalization 9.3 Polymorphism & Dynamic Method Binding RTTI and Introspection 9.4 RTTI and Introspection

32 32 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. base.getClass().toString());11. base.getClass().toString()); 12. System.out.println("Class for derived object = " +12. System.out.println("Class for derived object = " + 13. derived.getClass().toString());13. derived.getClass().toString());

33 33 RTTI and Introspection Run-time type identification make it possible to determine the type of an objectRun-time type identification make it possible to determine the type of an object –E.g. given a pointer to a base class, determine the derived class of the pointed object –The type (class) must be known at compile time Introspection makes general class information available at run-timeIntrospection makes general class information available at run-time –The type (class) does not have to be known at compile time –This is very useful in component architectures and visual programming –E.g. list the attributes of an object

34 34 RTTI and Introspection RTTI and introspection are powerful programming language featuresRTTI and introspection are powerful programming language features –They enables some powerful design techniques –We will discuss them in the context of Java This discussion will follow Chapter 12 in Thinking in Java by Bruce EckelThis discussion will follow Chapter 12 in Thinking in Java by Bruce Eckel –http://www.codeguru.com/java/tij/tij0119.shtml http://www.codeguru.com/java/tij/tij0119.shtml –By the way, this is an excellent book freely available on- line

35 35 The need for RTTI Polymorphism Example //: Shapes.java package c11; import java.util.*; interface Shape { void draw(); void draw();} class Circle implements Shape { public void draw() { public void draw() { System.out.println("Circle.draw()"); System.out.println("Circle.draw()"); }} class Square implements Shape { public void draw() { public void draw() { System.out.println("Square.draw()"); System.out.println("Square.draw()"); }} class Triangle implements Shape { public void draw() { public void draw() { System.out.println("Triangle.draw()"); System.out.println("Triangle.draw()"); }} 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) Poly- morphism What if you want to known the exact type at run-time?

36 36 The Class Object Type information is available at run-time in JavaType information is available at run-time in Java There is a Class object for each class in the programThere is a Class object for each class in the program –It stores class information Class objects are loaded in memory the first time they are needed by finding the.class file with that nameClass objects are loaded in memory the first time they are needed by finding the.class file with that name –The static initialization is performed upon class loading –A Java program is not completely loaded before it begin! The class Class provides a number of useful methods for RTTIThe class Class provides a number of useful methods for RTTI –http://java.sun.com/j2se/1.3/docs/api/java/lang/Class.html http://java.sun.com/j2se/1.3/docs/api/java/lang/Class.html

37 37 Example class Candy { static { static { System.out.println("Loading Candy"); System.out.println("Loading Candy"); }} class Gum { static { static { System.out.println("Loading Gum"); System.out.println("Loading Gum"); }} class Cookie { static { static { System.out.println("Loading Cookie"); System.out.println("Loading Cookie"); }} public class SweetShop { public static void main(String[] args) { public static void main(String[] args) { System.out.println("inside main"); System.out.println("inside main"); new Candy(); new Candy(); System.out.println("After creating Candy"); System.out.println("After creating Candy"); try { try { Class.forName("Gum"); Class.forName("Gum"); } catch(ClassNotFoundException e) { } catch(ClassNotFoundException e) { e.printStackTrace(); e.printStackTrace(); } System.out.println( "After Class.forName(\"Gum\")"); System.out.println( "After Class.forName(\"Gum\")"); new Cookie(); new Cookie(); System.out.println("After creating Cookie"); System.out.println("After creating Cookie"); }} Executed at Load Time Returns a reference to class Gum

38 38 Example OutputOutput –JVM-1 inside main Loading Candy After creating Candy Loading Gum After Class.forName("Gum") Loading Cookie After creating Cookie

39 39 Example OutputOutput –JVM-2 Loading Candy Loading Cookie inside main After creating Candy Loading Gum After Class.forName("Gum") After creating Cookie

40 40 The Class Object Class literals also provide a reference to the Class objectClass literals also provide a reference to the Class object –E.g. Gum.class Each object of a primitive wrapper class has a standard field called TYPE that also provides a reference to the Class objectEach object of a primitive wrapper class has a standard field called TYPE that also provides a reference to the Class object –http://java.sun.com/j2se/1.3/docs/api/java/lang/Boolean.ht ml http://java.sun.com/j2se/1.3/docs/api/java/lang/Boolean.ht mlhttp://java.sun.com/j2se/1.3/docs/api/java/lang/Boolean.ht ml

41 41 RTTI The type of a object can be determined using the instanceof keywordThe type of a object can be determined using the instanceof keyword –an operator, not a function –Notice that an object of a derived class is an instance of the its base classes (i.e. any predecessor in the inheritance hierarchy) RTTI is very useful when reusing classes without extending themRTTI is very useful when reusing classes without extending them Class.isInstance() also implements the instanceof functionalityClass.isInstance() also implements the instanceof functionality –if ( Class.forName ( classNameString ).isInstance ( myObject ) ) …

42 42 Introspection Introspection makes general class information available at run-timeIntrospection makes general class information available at run-time –The type (class) does not have to be known at compile time –E.g. list the attributes of an object This is very useful inThis is very useful in –Rapid Application Development (RAD) »Visual approach to GUI development »Requires information about component at run-time –Remote Method Invocation (RMI) »Distributed objects

43 43 Reflection Java supports introspection through its reflection libraryJava supports introspection through its reflection library –http://java.sun.com/j2se/1.3/docs/api/java/lang/reflect/pack age-summary.html http://java.sun.com/j2se/1.3/docs/api/java/lang/reflect/pack age-summary.htmlhttp://java.sun.com/j2se/1.3/docs/api/java/lang/reflect/pack age-summary.html –See classes Field (attributes), Method and Constructor Examples:Examples: –ShowMethods.java

44 44 Python The Inspect module provides introspections mechanismThe Inspect module provides introspections mechanism –http://www.python.org/doc/current/lib/module- inspect.html http://www.python.org/doc/current/lib/module- inspect.htmlhttp://www.python.org/doc/current/lib/module- inspect.html –See: »getmembers(object[, predicate]) »getsource(object) »getclasstree(classes[, unique]) »getmro(cls)


Download ppt "1 Data Abstraction and Object Orientation. 2 Chapter 9: Data Abstraction and Object Orientation 9.1 Encapsulation and Inheritance 9.2 Initialization and."

Similar presentations


Ads by Google