Download presentation
Presentation is loading. Please wait.
1
Object-Oriented Programming
Objects were first introduced in Simula 67 the intent in Simula was not to provide a new programming paradigm, but instead to offer a construct to easily build models for simulation purposes OOP was developed fully in Smalltalk objects can be thought of as extensions to the ADT except that the structure can be extended hierarchically for easy class modification message-passing instead of function calls encapsulation enforced through the class construct while methods are tied to classes, polymorphism allows classes to share methods when the classes are hierarchically related generic methods allow for a container’s data structure’s type(s) to vary
2
OOP Language Support Initially, OOP was only available in Smalltalk
by the end of the 80s, C++ and Common Lisp (via the Common Lisp Object System) added class definitions neither followed closely to what Smalltalk promoted multiple inheritance complex ways to control inheritance mixture of objects and non-objects, methods and functions CLOS was even less similar in that methods were not encapsulated with classes Ada 95 introduced a variation of the class (Ada 95 = Ada 83 + objects) Java and C# introduce a newer generation of OOPLs related to C++ but cleaner and easier to understand scripting languages started adding objects with JavaScript and has continued with both Python and Ruby (Ruby is the only pure OOPL since Smalltalk) other recent languages are OO like F#
3
OOPL Definitions Pure OOP: all computation done by message passing and all data in the language are stored as objects Hybrid OOP: computation shared between message passing and function calls most OOPLs are hybrid languages C++, CL, Ada95, Delphi are because they add classes on top of the existing language Java would be pure if not for the 8 primitive types supposedly the only pure OOPLs are Smalltalk and Ruby although others have made the claim
4
OOPL Features Inheritance: solves the modification problem
controls what definitions a subclass obtains from its parent class(es) to control inheritance, the language might include modifiers such as private, public and protected question: can a subclass override a parent’s definition (whether the data structure or the methods)? if so, can the parent item still be accessed or is it hidden? question: is multiple inheritance available? (C++ and CLOS have this) Polymorphism: variables can reference any subclass of a given class we need a mechanism to bind a message to the proper method often done at run time so is called dynamic type binding
5
Dynamic Type Binding If a variable can be polymorphic and a method has been overridden then at compile time, we may not know which method a message refers to for instance, if SomeClass inherits from SomeParent and someMethod is overridden, then is the message below of SomeClass or SomeParent? SomeClass a = new SomeClass( ); … a.someMethod( ); this can only be determined at compile time if the method cannot be overridden (e.g., it is final) the method is not overridden, but overloaded (a different parameter profile) otherwise, it is handled at run-time so is dynamically bound
6
Example In C++, a virtual method in Shape is implemented
in two subclasses and redefined in a subsubclass A variable of type Rectangle can take on a Square and therefore var.draw must be dynamically bound
7
Entities of a Class Classes contain methods and variables
instance variables are uniquely stored in each object of the class class variables are shared among all objects of the class (these are less commonly used) methods are divided into class methods and instance methods the main distinction is usually that class methods cannot operate on instance variables classes also may have defined constants If a class inherits a method from a parent class, is the method that of the parent, or a copy? that is, is the method contained within this class (thus a copy) or is the message routed to the parent class’ method?
8
Class/Subclass Relationships
Aside from C++ and Common Lisp, classes in other languages must have one (and only one) parent every defined class needs a parent such languages will offer a starting class, usually called Object a class can be defined such that it is not specific enough to have an implementation for its methods this requires making the class abstract (or virtual) the role of the defined but unimplemented methods is to force the child classes to implement them this approach is used to create the interface (for instance in Java) the interface is a target of which the subclass must implement an interface provides a form of multiple inheritance in that the class inherits from its parent and methods from interface classes classes with abstract entities cannot themselves be instantiated, but can be extended into subclasses
9
Design Issues Exclusitivity of objects Subclass relationships
are there other types aside from objects? (is communication message passing or hybrid) as mentioned, Ruby and Smalltalk have exclusitivity C++ and Common Lisp not only are hybrids, they also allow for stand-alone objects (not related to a parent) Subclass relationships is a subclass a descendant of the class (is-a relationship) we expect children to behave like parents this permits polymorphism is some other relationship permitted like subset or subrange?
10
Continued Are the following available and if so, how are they provided? inheritance information hiding type checking polymorphism we think of these as necessary for OOPLs but CLOS does not include information hiding and dynamic languages may not provide type checking Single vs. multiple inheritance which is allowed? Allocation and deallocation of objects heap or other? explicit or garbage collected? Can class definitions be nested?
11
Smalltalk Programs consist only of objects and messages
variables are local (private) or global (shared) all vars are pointed too by ptrs only single inheritance, subclasses inherit everything from parent where class methods and class variables can be overridden in a derived class parent methods/data still accessible using super Dynamic binding for polymorphism when a method is called, a search takes place at the child’s location for that method’s definition if not found, the search continues up the hierarchy until the method’s definition is found (if none found, error) we cover smalltalk syntax separately We explore details of Smalltalk in a separate text file
12
C++ Adds classes to C as well as cleaning up some poorer implemented aspects of C such as adding pass by reference Although cited as C + Smalltalk, its implementation of classes/objects is very different classes can either be a derived class or stand alone multiple inheritance is available some or all data and methods can be inherited from base class(es) objects can be either stack dynamic or heap dynamic (these require a destructor method to deallocate memory) C++ was the most used OOPL in spite of (or maybe because of) having complex object-oriented mechanisms this may have changed recently with Java and C# catching up
13
Controlling Inheritance in C++
Class members can be private, protected or public private members are only accessible by member functions and friends of the class friends are functions/classes explicitly declared as friends by the given class we might use a friend to provide access similar to having access to the data structure of a nested inner class in Java public members are accessible by any function protected members are like private members except that derived classes can modify access rights for inheriting members
14
C++ Example class base_class { private: int a; float x;
protected: int b; float y; public: int c; float z; } class sub1 : public base_class {…}; class sub2 : private base_class in sub1: b and y are protected, c and z are public in sub2: b, y, c and z are private, no derived class of sub2 has access them, a and x are not accessible to either sub1 or sub2 Note that since sub2 is a derived private class, no member of the parent class is explicitly visible, and so b, c, y and z must be re-exported to be used in an instance of sub2 This is done using : : as in base_class : : c;
15
Example class single_linked_list { class node {
friend class single_linked_list; private: node *link; int contents; }; single_linked_list( ) {head = 0}; void inset_at_head(int); void insert_at_tail(int); int remove_at_head( ); int empty( ); Make single_linked_list a friend of node so the private portion of node can be accessed directly by single_linked_list Or, avoid doing this by adding an interface to the node class
16
class stack : public single_linked_list { public: stack( ) { }
void push(int value) { single_linked_list::insert_at_head(value); } int pop( ) { single_linked_list::remove_at_head( ); }; class queue : public single_linked_list { queue( ) { } void enqueue(int value) { single_linked_list::insert_at_tail(value); int dequeue( ) { Here, we inherit from single_linked_list to create stack and queue classes. Both implementations suffer in that an instance of either could actually access any element in the list because they were declared as public. Changing public single_linked_list to private single_linked_list would resolve this issue.
17
C++ Object Binding Objects can be referenced through ordinary variables these objects are stack dynamic and all method calls would be statically bound Otherwise, objects are referenced via pointers these objects are heap dynamic any pointer of a class can point at any derived class of that class thus, pointers can be polymorphic variables but non-pointers cannot if the variable is polymorphic then method calls are dynamically bound any method that will be dynamically bound must be declared as a virtual function (see the notes section for an example) Example of a virtual function public class shape { public: virtual void draw( ) = 0; // indicates that draw is a pure virtual function } // that is, that there is no implementation here // so shape is an abstract class public class circle : public shape { virtual void draw( ) {…} } public class rectangle : public shape { public class square : public rectangle { square s; // s is dynamically rectangle r; // bound to draw shape &ref_shape = s; ref_shape.draw( ); // whereas r is statically r.draw( ); // bound to draw
18
Java We skip most of the detail here as you are all familiar with Java
all entities in Java are objects except for the primitive types Java restricts inheritance to single inheritance multiple inheritance is not available but somewhat simulated via interfaces nested classes are available, inner classes are hidden from classes that are not the outer class objects are heap dynamic and pointed to by reference variables all method calls are dynamically bound unless a class is denoted as final Java includes a finalize method that will be invoked before the object’s memory is returned to the heap while avoiding a destructor by using garbage collection Java is simpler and less powerful than C++ but safer
19
C# C# offers constructs for the class (similar to Java) and struct (similar to C++) structs are stack dynamic, objects are heap dynamic C#’s syntax is more like C++ for class definitions, for example: public class NewClass : ParentClass {…} dynamic binding is done only if methods are specially indicated as virtual where overridden methods in derived classes must be specially indicated through the word override like Java, C# offers only single inheritance and all classes must have a parent (no stand-alone classes) with the parent class defaulting to Object the Object class implements ToString, Finalize and Equals, which are inherited to all classes also like Java, C# permits nested classes
20
Objects in Ada 95 Ada 83 included the Package for encapsulating ADTs
objects were added for Ada 95 as an extension to ADTs objects were called a tagged type tagged types are either records or private types records which are public (no information hiding) private types (true objects) packages can be separately compiled giving Ada 95 the ability to offer classes much like Java, C++, and C# Ada offers both static and dynamic binding of objects to procedure calls dynamic binding is available through the tagged type’s classwide type denoted as Name’class or by using a polymorphic variable
21
More on Ada 95 Objects No implicit calling of constructors and destructors if desired, any constructor destructor is a procedure (not a method) explicitly invoked by the user code as Ada would automatically handle allocation and deallocation, neither are needed Single inheritance multiple inheritance can be simulated to some extent using generic classes Subclasses inherit all items from a parent class to restrict this, you would have to use child library packages (nested directly inside of the parent’s package)
22
Ada Example Package PERSON_PKG is type PERSON is tagged private;
procedure DISPLAY(P : in out PERSON); private type PERSON is tagged record NAME : STRING(1..30); ADDRESS : STRING(1..30); AGE : INTEGER; end record; end PERSON_PKG; with PERSON_PKG; use PERSON_PKG; Package STUDENT_PKG is type STUDENT is new PERSON with GRADE_POINT_AVERAGE : FLOAT; GRADE_LEVEL : INTEGER; procedure DISPLAY (ST: in STUDENT); end STUDENT_PKG; Ada Example DISPLAY is being overridden from person_PKG
23
Continued P : PERSON; S : STUDENT; Pcw : PERSON’class; // classwide
… // version of Person DISPLAY(P); // call Person’s display DISPLAY(S); // call Student’s display Pcw := P; DISPLAY(Pcw); // Person’s display Pcw := S; DISPLAY(Pcw); // Student’s display Ada’s mechanisms for objects is built on top of previous mechanisms and so is both awkward and less flexible than C++, and inconsistent as compared to Java/C#
24
Objective-C Designed at about the same time as C++, both are C + OO but they implement OOP very differently Obj-C is more like Smalltalk in its implementation Early Objective-C was implemented to be preprocessed by the C compiler and have the C compiler convert the Objective-C code into C! the C compiler would then compile the C code One similarity between Objective-C and C++ is that they both permit functions and objects that is, you can have stand-alone objects there are also structs giving you similar flexibility as to C++
25
Classes in Objective-C
Class definitions consist of interface and implementation these are often separated into two files requiring the implementation file to #import the interface file instance variables declared in the interface no class variables but static global variables are available giving the same functionality only single inheritance with root class being NSObject use the same three visibility modifiers: public, private, protected, much like in C# objects are allocated from the heap (no stack objects)
26
Dynamic Typing Objective-C allows run-time type introspection
at run-time, an object can be tested for its type and based on its time, decide what to do this causes a lot of dynamic type binding when using polymorphic variables – in C++, as much compile-time type checking is handled as possible in fact, in Objective-C, polymorphic variables are specifically declared to be polymorphic declare the variable to be of type id as in id polymorphVariable; this allows you to declare variables that can take on any type of object - which makes the language a little less safe
27
Unique to Objective-C In Objective-C, interfaces are called protocols and are similar to what we’ve seen in Java with one exception you can define optional methods in a protocol in which case they do not need to be implemented An innovation of Objective-C is the category this let’s you add methods to an existing class without extending it you can add a category to a class even if you don’t have the class’ source code Classes are objects which can receive messages We see this style also used in Smalltalk and Common Lisp to an extent
28
Ruby Like Smalltalk, everything in Ruby is an object and all computation is done via message passing class definitions are executable, meaning that a class’ definition (data, methods) can change at run time for instance, you could have code that modifies a class at run-time so that the class gains a new method at run-time, a class is the union of all definitions that have been executed all variables are reference variables to objects and all are typeless instance variable names are denoted by starting instance variables are always private (accessor methods must be written if you want to provide external access to an instance variable)
29
Continued Methods default to public, but can be private or protected
Accessor/mutator methods can be easily generated by using the shortcut functions attr_reader and attr_writer respectively for instance: attr_reader :member1, :member2 will automatically generate a getter method to return the value of member1 Deriving a subclass is done through < as in class subclass < parentclass access control to methods can be changed at the subclass level (for instance, if subclass above inherits method foo, subclass can alter the access control from public to private or protected)
30
Continued The Ruby module is used to control encapsulation and namespaces All variables are polymorphic (they are typeless and so only bound to a given object when assigned to point at it) and are therefore dynamically bound to methods While Ruby is a pure OOPL (and therefore will satisfy some OO programmers), it is generally a weaker language than C++, Java or C# in that it lacks the ability to more tightly control what is inherited and how (no multiple inheritance) access control other OOPL features like abstract classes
31
JavaScript JavaScript – primarily used for dynamic html pages, similar in some ways to Java syntax and contains both objects and primitive data types (same control structures, same type of assignment statements/shortcut operators) but from there, the treatment of objects differs in many ways: Java JavaScript Statically typed, all variables require declarations Dynamically typed (no explicit typing, variables do need to be declared), variables can reference any type, all variables are reference types All code encapsulated in classes No classes, only code + functions + objects (one of a kind classes), therefore no inheritance or polymorphism
32
JavaScript Objects Objects have a collection of properties
Each datum is a name/value pair Methods (functions) to operate on the given datum Instance data are added to objects dynamically using the notation var.member = value; Objects can be nested inside of other objects someObject.someMember = new Object( ); someObject.someMember.someInternetMember = value; To remove from an object, use delete as in delete someObject; Constructors are just functions that initialize members of an object where the constructor name is the name of the object JavaScript is not intended for large-scale applications and you generally would not use it for an OOP project
33
DESIGN ISSUE C++ JAVA C# RUBY Exclusivity of objects
SMALLTALK C++ OBJECTIVE-C JAVA C# RUBY Exclusivity of objects All data are objects Primitive types plus objects Are subclasses subtypes? Yes and they usually are If derivation is public No subclasses are subtypes Single and multiple inheritance Single only Both Single only, but some effects with protocols Single only, but some effects with interfaces Single only, but some effects with modules Allocation and deallocation of objects Explicit heap allocated; deallocation is implicit Static, stack dynamic, or heap dynamic; allocation and deallocation are explicit All objects are heap dynamic; allocation is explicit and deallocation is implicit Dynamic and static binding All method bindings are dynamic Method binding can be either Nested classes? No Yes Initialization Constructors explicitly called Constructors are implicitly called
34
Implementing Objects Need at least two mechanisms for object construction and use description of data storage pointers to the object’s methods if dynamically bound, the method call can quickly be made These can be captured using a compiler-generated CIR class instance record any newly instantiated object uses the CIR as a template to generate the storage space needed for the object CIR contains pointers to methods What about polymorphic variables? what methods do their CIRs point to? use a virtual method table for each class (differs for a subclass) and have the CIR point to that VMT (see next slide)
35
Example of CIRs public class A { public int a, b;
public void draw( ) {…} public int area( ) {…} } public class B extends A { public int c, d; public void sift() {…} This becomes more complicated if multiple inheritance is allowed
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.