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

Slides:



Advertisements
Similar presentations
Lecture 10: Part 1: OO Issues CS 540 George Mason University.
Advertisements

1 Object Lifetime and Garbage Collection (Section 10.3 & 7.7) CSCI 431 Programming Languages Fall 2003 A modification of slides developed by Felix Hernandez-Campos.
1 Object-Oriented Programming (Section ) CSCI 431 Programming Languages Fall 2003 A compilation of material developed by Felix Hernandez-Campos.
CS 211 Inheritance AAA.
Chapter 12: Support for Object-Oriented Programming
ITEC200 – Week03 Inheritance and Class Hierarchies.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lecture 23: Object Lifetime and Garbage Collection COMP 144 Programming Language Concepts.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
1 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lecture 24: Dynamic Binding COMP 144 Programming Language Concepts Spring 2002 Felix Hernandez-Campos.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
1 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lecture 22: Object-Oriented Programming COMP 144 Programming Language Concepts Spring 2002.
Chapter 10 Classes Continued
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Inheritance and Polymorphism CS351 – Programming Paradigms.
CS 355 – PROGRAMMING LANGUAGES Dr. X. Copyright © 2012 Addison-Wesley. All rights reserved.1-2 Chapter 12 Topics Introduction Object-Oriented Programming.
Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 Inheritance Inheritance is a fundamental object-oriented design technique used to.
OOP Languages: Java vs C++
Comparison of OO Programming Languages © Jason Voegele, 2003.
Programming Languages and Paradigms Object-Oriented Programming.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
OOPs Object oriented programming. Based on ADT principles  Representation of type and operations in a single unit  Available for other units to create.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
1 Chapter 10: Data Abstraction and Object Orientation Aaron Bloomfield CS 415 Fall 2005.
Object Oriented Programming: Java Edition By: Samuel Robinson.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
Programming Languages and Paradigms Object-Oriented Programming.
Guided Notes Ch. 9 ADT and Modules Ch. 10 Object-Oriented Programming PHP support for OOP and Assignment 4 Term project proposal C++ and Java Designer.
OOP and Dynamic Method Binding Chapter 9. Object Oriented Programming Skipping most of this chapter Focus on 9.4, Dynamic method binding – Polymorphism.
Inheritance in the Java programming language J. W. Rider.
Introduction to Object Oriented Programming CMSC 331.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Lecture 10 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea.
CS451 - Lecture 2 1 CS451 Lecture 2: Introduction to Object Orientation Yugi Lee STB #555 (816) * Acknowledgement:
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 12 Support for Object-Oriented Programming.
Object-Oriented Programming Chapter Chapter
(1) ICS 313: Programming Language Theory Chapter 12: Object Oriented Programming.
OOPs Object oriented programming. Abstract data types  Representationof type and operations in a single unit  Available for other units to create variables.
Object Oriented Programming
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
ISBN Object-Oriented Programming Chapter Chapter
Copyright © 2005 Elsevier Object-Oriented Programming Control or PROCESS abstraction is a very old idea (subroutines!), though few languages provide it.
1 Lecture 22: Object Lifetime and Garbage Collection (Section 10.3 & 7.7) CSCI 431 Programming Languages Fall 2002 A modification of slides developed by.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Inheritance ndex.html ndex.htmland “Java.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
1 Lecture 23: Dynamic Binding (Section ) CSCI 431 Programming Languages Fall 2002 A compilation of material developed by Felix Hernandez-Campos.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
CSCI-383 Object-Oriented Programming & Design Lecture 17.
ISBN Chapter 12 Support for Object-Oriented Programming.
Chapter 12: Support for Object- Oriented Programming Lecture # 18.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Design issues for Object-Oriented Languages
C11, Implications of Inheritance
Modern Programming Tools And Techniques-I
Chapter 9 :: Data Abstraction and Object Orientation
CS212: Object Oriented Analysis and Design
Types of Programming Languages
Copyright © 2009 Elsevier Chapter 9 :: Data Abstraction and Object Orientation Programming Language Pragmatics Michael L. Scott.
More Object-Oriented Programming
Support for Object-Oriented Programming
Lecture 10 Concepts of Programming Languages
Chapter 10 :: Object Orientated Programming
Presentation transcript:

1 Data Abstraction and Object Orientation

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 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 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 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 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? » –And in Python? » http://

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 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 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 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 Constructors in Eiffel ComplexNumbersClass Constructors (!! equals new) Explicit Constructor Declaration

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

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 Java Example See Java Language SpecificationSee Java Language Specification – sses.doc.html# sses.doc.html#41652http://java.sun.com/docs/books/jls/second_edition/html/cla sses.doc.html#41652 – pressions.doc.html# pressions.doc.html#23302http://java.sun.com/docs/books/jls/second_edition/html/ex pressions.doc.html#23302

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 C++ Example In general, C++ destructors are used for manual storage reclamationIn general, C++ destructors are used for manual storage reclamationDestructor

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 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 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 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 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 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 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 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 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 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 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 Dynamic Method Binding Non-Repeated Multiple Inheritance

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 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 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 1. public class Base {1. public class Base { 2. }2. } 3. public class Derived extends Base {3. public class Derived extends Base { 4. }4. } // 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(); System.out.println("Class for base object = " +10. System.out.println("Class for base object = " base.getClass().toString());11. base.getClass().toString()); 12. System.out.println("Class for derived object = " +12. System.out.println("Class for derived object = " derived.getClass().toString());13. derived.getClass().toString());

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 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 – –By the way, this is an excellent book freely available on- line

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 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 –

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 Example OutputOutput –JVM-1 inside main Loading Candy After creating Candy Loading Gum After Class.forName("Gum") Loading Cookie After creating Cookie

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

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 – ml mlhttp://java.sun.com/j2se/1.3/docs/api/java/lang/Boolean.ht ml

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 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 Reflection Java supports introspection through its reflection libraryJava supports introspection through its reflection library – age-summary.html 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 Python The Inspect module provides introspections mechanismThe Inspect module provides introspections mechanism – inspect.html inspect.htmlhttp:// inspect.html –See: »getmembers(object[, predicate]) »getsource(object) »getclasstree(classes[, unique]) »getmro(cls)