Kĩ thuật lập trình - Chapter 13: Object - Oriented programming

Imperative programming paradigm Algorithms + Data Structures = Programs [Wirth] Produce a program by functional decomposition Start with function to be computed Systematically decompose function into more primitive functions Stop when all functions map to program statements

ppt52 trang | Chia sẻ: huyhoang44 | Lượt xem: 739 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Kĩ thuật lập trình - Chapter 13: Object - Oriented programming, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
Programming Languages 2nd edition Tucker and NoonanChapter 13Object-Oriented ProgrammingI am surprised that ancient and Modern writers have not attributed greater importance to the laws of inheritance ... Alexis de TocquevilleContents13.1 Prelude: Abstract Data Types13.2 The Object Model13.3 Smalltalk13.4 Java13.5 Python Ask not what you can dofor your classes,Ask what your classes can dofor you.Owen Astrachan13.1 Prelude: Abstract Data TypesImperative programming paradigmAlgorithms + Data Structures = Programs [Wirth]Produce a program by functional decompositionStart with function to be computedSystematically decompose function into more primitive functionsStop when all functions map to program statements Procedural AbstractionConcerned mainly with interfaceFunctionWhat it computesIgnore details of how Example: sort(list, length);Data AbstractionOr: abstract data typesExtend procedural abstraction to include dataExample: type floatExtend imperative notion of type by:Providing encapsulation of data/functionsExample: stack of int'sSeparation of interface from implementationDefn: Encapsulation is a mechanism which allows logically related constants, types, variables, methods, and so on, to be grouped into a new entity.Examples:ProceduresPackagesClassesA Simple Stack in CFigure 13.1A Stack Type in CFigure 13.2Implementation of Stack Type in CFigure 13.3Goal of Data AbstractionPackageData typeFunctionsInto a module so that functions provide:public interfacedefines typegeneric type element is private;package stack_pck is type stack is private; procedure push (in out s : stack; i : element); procedure pop (in out s : stack) return element; procedure isempty(in s : stack) return boolean; procedure top(in s : stack) return element;private type node; type stack is access node; type node is record val : element; next : stack; end record;end stack_pck;package body stack_pck is procedure push (in out s : stack; i : element) is temp : stack; begin temp := new node; temp.all := (val => i, next => s); s := temp; end push; procedure pop (in out s : stack) return element is temp : stack; elem : element; begin elem := s.all.val; temp := s; s := temp.all.next; dispose(temp); return elem; end pop; procedure isempty(in s : stack) return boolean is begin return s = null; end isempty; procedure top(in s : stack) return element is begin return s.all.val; end top;end stack_pck;13.2 The Object ModelProblems remained:Automatic initialization and finalizationNo simple way to extend a data abstractionConcept of a classObject decomposition, rather than function decompositionDefn: A class is a type declaration which encapsulates constants, variables, and functions for manipulating these variables.A class is a mechanism for defining an ADT.class MyStack { class Node { Object val; Node next; Node(Object v, Node n) { val = v; next = n; } } Node theStack; MyStack( ) { theStack = null; } boolean empty( ) { return theStack == null; }Object pop( ) { Object result = theStack.val; theStack = theStack.next; return result; } Object top( ) { return theStack.val; } void push(Object v) { theStack = new Node(v, theStack); }}ConstructorDestructorClient of a classClass methods (Java static methods)Instance methodsOO program: collection of objects which communicate by sending messagesGenerally, only 1 object is executing at a timeObject-based language (vs. OO language)ClassesDetermine type of an objectPermit full type checkingVisibilitypublicprotectedprivateInheritanceClass hierarchySubclass, parent or super classis-a relationshipA stack is-a kind of a listSo are: queue, deque, priority queuehas-a relationshipIdentifies a class as a client of another classAggregationA class is an aggregation if it contains other class objectsIn single inheritance, the class hierarchy forms a tree.Rooted in a most general class: ObjectInheritance supports code reuseRemark: in Java a Stack extends a Vector Good or bad idea? Why?Single inheritance languages: Smalltalk, JavaMultiple InheritanceAllows a class to be a subclass of zero, one, or more classes.Class hierarchy is a directed graphAdv: facilitates code reuseDisadv: more complicated semanticsRe: Design Patterns book mentions multiple inheritance in conjunction with only two of its many patterns.Defn: A language is object-oriented if it supports an encapsulation mechanism with information hiding for defining abstract data types,virtual methods, andinheritancePolymorphismPolymorphic - having many formsDefn: In OO languages polymorphism refers to the late binding of a call to one of several different implementations of a method in an inheritance hierarchy.Consider the call: obj.m( );obj of type TAll subtypes must implement method m( )In a statically typed language, verified at compile timeActual method called can vary at run time depending on actual type of obj for (Drawable obj : myList) obj.paint( );// paint method invoked varies// each graphical object paints itself// essence of OOPDefn: A subclass method is substitutable for a parent class method if the subclass’s method performs the same general function.Thus, the paint method of each graphical object must be transparent to the caller.The code to paint each graphical object depends on the principle of substitutability.PolymorphismEssence: same call evokes a different method depending on class of objectEx: obj.paint(g);ButtonPanelChoice BoxSubstitutability principleTemplates or GenericsA kind of class generatorCan restrict a Collections class to holding a particular kind of objectDefn: A template defines a family of classes parameterized by one or more types.Prior to Java 1.5, clients had to downcast an object retrieved from a Collection class.ArrayList list = new ArrayList ();...for (Drawable d : list) d.paint(g);Abstract ClassesDefn: An abstract class is one that is either declared to be abstract or has one or more abstract methods.Defn: An abstract method is a method that contains no code beyond its signature.Any subclass of an abstract class that does not provide an implementation of an inherited abstract method is itself abstract.Because abstract classes have methods that cannot be executed, client programs cannot initialize an object that is a member an abstract class. This restriction ensures that a call will not be made to an abstract (unimplemented) method.abstract class Expression { ... } class Variable extends Expression { ... } abstract class Value extends Expression { ... } class IntValue extends Value { ... } class BoolValue extends Value { ... } class FloatValue extends Value { ... } class CharValue extends Value { ... } class Binary extends Expression { ... } class Unary extends Expression { ... }InterfacesDefn: An interface encapsulates a collection of constants and abstract method signatures.An interface may not include either variables,constructors, or non-abstract methods.public interface Map { public abstract boolean containsKey(Object key); public abstract boolean containsValue(Object value); public abstract boolean equals(Object o); public abstract Object get(Object key); public abstract Object remove(Object key); ...}Because it is not a class, an interface does not have a constructor, but an abstract class does.Some like to think of an interface as an alternativeto multiple inheritance. Strictly speaking, however, an interface is not quite the same since it doesn't provide a means of reusing code;i.e., all of its methods must be abstract.An interface is similar to multiple inheritancein the sense that an interface is a type.A class that implements multiple interfacesappears to be many different types,one for each interface.Virtual Method Table (VMT)How is the appropriate virtual method is called at run time.At compile time the actual run time class of any object may be unknown.MyList myList; ...System.out.println(myList.toString( ));Each class has its own VMT, with each instance of the class having a reference (or pointer) to the VMT. A simple implementation of the VMT would be a hash table, using the method name (or signature, in the case of overloading) as the key and the run time address of the method invoked as the value.For statically typed languages, the VMT is kept as an array. The method being invoked is converted to an indexinto the VMT at compile time.class A { Obj a; void am1( ) { ... } void am2( ) { ... }}class B extends A { Obj b; void bm1( ) { ... } void bm2( ) { ... } void am2( ) { ... }} Run Time Type IdentificationDefn: Run time type identification (RTTI) is the ability of the language to identify at run time the actual type or class of an object. All dynamically typed languages have this ability, whereas most statically typed imperative languages, such as C, lack this ability. At the machine level, recall that data is basically untyped.In Java, for example, given any object reference, we can determine its class via:Class c = obj.getClass( );ReflectionReflection is a mechanism whereby a program can discover and use the methods of any of its objects and classes.Reflection is essential for programming tools that allow plugins (such as Eclipse -- www.eclipse.org) and for JavaBeans components.In Java the Class class provides the following information about an object:The superclass or parent class.The names and types of all fields.The names and signatures of all methods.The signatures of all constructors.The interfaces that the class implements.Class class = obj.getClass( );Constructor[ ] cons = class.getDeclaredConstructors( );for (int i=0; i 0) System.out.print(", "); System.out.print(param[j].getName( ); } System.out.println( ")" );}

Các file đính kèm theo tài liệu này:

  • pptch13a_7408.ppt