670 likes | 685 Views
Understand object-oriented programming concepts such as classes, inheritance, polymorphism, and reflection. Explore class syntax and examples in Oz while learning about creating objects and functors. Discover how to use inheritance to build hierarchical structures of ADTs incrementally with delegation and visibility considerations.
E N D
Object-Oriented ProgrammingInheritance (VRH 7.3-4)Object System Implementation/Java(VRH 7.6-7) Carlos Varela RPI Adapted with permission from: Seif Haridi KTH Peter Van Roy UCL C. Varela; Adapted from S. Haridi and P. Van Roy
Overview • What is object-oriented programming? • Stateful (imperative) model (revisited) • Objects • Classes • Interfaces • Inheritance • Polymorphism • Static and dynamic binding • Multiple Inheritance • Reflection • Relationship to Other Programming Models • Active Objects C. Varela; Adapted from S. Haridi and P. Van Roy
Classes in Oz (simplified syntax) A class is a statement classClassVariable attr AttrName1 : AttrNameN meth Pattern1 Statement end : meth PatternN Statement end end C. Varela; Adapted from S. Haridi and P. Van Roy
Classes in Oz (Example) The class Counter has the syntactic form class Counterattr valmeth display {Browse @val}endmeth inc(Value) val := @val + Valueendmeth init(Value) val := Valueendend C. Varela; Adapted from S. Haridi and P. Van Roy
Example • The following shows how an object is created from a class using the procedure New/3, whose first argument is the class, the second is the initial method, and the result is the object. • New/3 is a generic procedure for creating objects from classes. declare C = {New Counter init(0)}{C display}{C inc(1)}{C display} Object interface is as a procedure of one argument, which expects a record representing a method C. Varela; Adapted from S. Haridi and P. Van Roy
Classes as functors functor Counter export inc:Incdisplay:Display init:Init define S proc {Init init(I)} S = {NewCell I}end proc {Inc Value}S := @S + Valueend proc {Display} {Browse @S} end end C. Varela; Adapted from S. Haridi and P. Van Roy
Pattern of use fun {New Functor Init} M in [M] = {Module.apply [Functor]} {M.init Init} M End declare C1 C2 C1 = {New Counter init(0)} C2 = {New Counter init(100)} {C1.inc 1} {C1.display} {C2.inc 10} {C2.display} Generic function to create objects from functors Object interface is a record with procedure values inside fields C. Varela; Adapted from S. Haridi and P. Van Roy
Classes as (higher-order) procedures fun {Counter} S proc {Inc inc(Value)}S := @S + Value end proc {Display display} {Browse @S} end proc {Init init(I)} S = {NewCell I} end D = o(inc:Inc display:Display init:Init) inproc{$ M} {D.{Label M} M} end end C. Varela; Adapted from S. Haridi and P. Van Roy
Pattern of use fun {New Class InitialMethod} O = {Class} in {O InitialMethod} O end declare C = {New Counter init(0)}{C display}{C inc(1)}{C display} Generic function to create objects from classes (procedures) Object interface is a procedure of one argument, which expects a record representing a message. C. Varela; Adapted from S. Haridi and P. Van Roy
Object-oriented programming • Supports • Encapsulation • Compositionality • Instantiation • Plus • Inheritance C. Varela; Adapted from S. Haridi and P. Van Roy
Inheritance • Programs can be built in hierarchical structure from ADT’s that depend on other ADT’s (Components) • Object-oriented programming (inheritance) is based on the idea that ADTs have so much in common • For example, sequences (stacks, lists, queues) • Object oriented programming enables building ADTs incrementally, through inheritance • An ADT can be defined to inherit from another abstract data type, substantially sharing functionality with that abstract data type • Only the difference between an abstract datatype and its ancestor has to be specified C. Varela; Adapted from S. Haridi and P. Van Roy
Classes as incremental ADTs • Object-oriented programming allows allows us to define a class by extending existing classes • Three things have to be introduced • How to express inheritance, and what does it mean? • How to access particular methods in the new class and in preexisting classes • Visibility – what part of the program can see the attributes and methods of a class • The notion of delegation as a substitute for inheritance C. Varela; Adapted from S. Haridi and P. Van Roy
Inheritance • Inheritance should be used as a way to specialize a class while retaining the relationship between methods • In this way it is a just an extension of an ADT • The other view is inheritance is just a (lazy) way to construct new abstract data types! • No relationships are preserved general class specialized class C. Varela; Adapted from S. Haridi and P. Van Roy
Inheritance class Account attr balance:0 meth transfer(Amount) balance := @balance+Amount end meth getBal(B) B = @balance end end A={New Account transfer(100)} C. Varela; Adapted from S. Haridi and P. Van Roy
Inheritance II The class VerboseAccount has the methods: transfer, getBal, and verboseTransfer Conservative extension class VerboseAccount from Account meth verboseTransfer(Amount) ... end end C. Varela; Adapted from S. Haridi and P. Van Roy
Inheritance II The class AccountWithFee has the methods: transfer, getBal, and verboseTransfer The method transfer has been redefined (overridden) with another definition Non-Conservative extension class AccountWithFee from VerboseAccount attr fee:5 meth transfer(Amount) ... end end C. Varela; Adapted from S. Haridi and P. Van Roy
Inheritance II Account Non-Conservative extension class AccountWithFee from VerboseAccount attr fee:5 meth transfer(Amount) ... end end VerboseAccount AccountWithFee C. Varela; Adapted from S. Haridi and P. Van Roy
Polymorphism Account The ability for operations to take objects (instances) of different types. For example, the transfer method can be invoked in account object instances of three different classes. The most specific behavior should be executed. VerboseAccount AccountWithFee C. Varela; Adapted from S. Haridi and P. Van Roy
Static and dynamic binding Dynamic binding • Inside an object O we want to invoke a method M • This is written as {self M}, and chooses the method visible in the current object (M of D) class C meth M class D a subclass of C meth M O an instance of D C. Varela; Adapted from S. Haridi and P. Van Roy
Static and dynamic binding Static binding • Inside an object O we want to invoke a method M in a specific (super) class • This is written as C, M and chooses the method visible in the super class C (M of C) class C meth M class D a subclass of C meth M O an instance of D C. Varela; Adapted from S. Haridi and P. Van Roy
Static method calls • Given a class and a method head m(…), a static method-call has the following form:C, m(…) • Invokes the method defined in the class argument. • A static method call can only be used inside class definitions. • The method call takes the current object denoted by self as implicit argument. • The method m could be defined in the class C, or inherited from a super class. C. Varela; Adapted from S. Haridi and P. Van Roy
Inheritance class Account attr balance:0 meth transfer(Amount) balance @balance+Amount end meth getBal(B) B = @balance end end A={New Account transfer(100)} C. Varela; Adapted from S. Haridi and P. Van Roy
Inheritance II The class VerboseAccount has the methods: transfer, getBal, and verboseTransfer Conservative extension class VerboseAccount from Account meth verboseTransfer(Amount) {selftransfer(Amount)} {Browse @balance} end end C. Varela; Adapted from S. Haridi and P. Van Roy
Inheritance II The class AccountWithFee has the methods: transfer, getBal, and verboseTransfer The method transfer has been redefined (overridden) with another definition Non-Conservative extension class AccountWithFee from VerboseAccount attr fee:5 meth transfer(Amount) VerboseAccount,transfer(Amount-@fee) end end C. Varela; Adapted from S. Haridi and P. Van Roy
Inheritance II Non-Conservative inheritance is dangerous because it might change the relationship between methods and the invariants the programmer depends on Non-Conservative extension class AccountWithFee from VerboseAccount attr fee:5 meth transfer(Amount) VerboseAccount,transfer(Amount-@fee) end end Account getBalance(B); transfer(S); getBalance(B1) => B1 = B+S C. Varela; Adapted from S. Haridi and P. Van Roy
Inheritance II Non-Conservative inheritance is dangerous because it might change the relationship between methods and the invariants the programmer depends on Non-Conservative extension class AccountWithFee from VerboseAccount attr fee:5 meth transfer(Amount) VerboseAccount,transfer(Amount-@fee) end end AccountWithFee getBalance(B); transfer(S); getBalance(B1) => B1 = B+S-@fee C. Varela; Adapted from S. Haridi and P. Van Roy
Inheritance III • Classes may inherit from one or several classes appearing after the keyword: from. • A class B is a superclass of a class A if: • B appears in the from declaration of A, or • B is a superclass of a class appearing in the from declaration of A. • The methods (attributes and features) available in a class C (i.e. visible) are defined through a precedence relation on the methods that appear in the class hierarchy based on the overriding relation: • A method in a class C overrides any method, with the same label, in any super class of C. C. Varela; Adapted from S. Haridi and P. Van Roy
SuperClass relation • SuperClass relation is directed and acyclic. C C. Varela; Adapted from S. Haridi and P. Van Roy
SuperClass relation • SuperClass relation is directed and acyclic. • After striking out all overridden methods each remaining method should have a unique label and is defined only in one class in the hierarchy. C C. Varela; Adapted from S. Haridi and P. Van Roy
Inheritance relation m m m A (valid hierarchy) m C (invalid hierarchy) C. Varela; Adapted from S. Haridi and P. Van Roy
Multiple Inheritance Example class Account attr balance:0 meth transfer(Amount) balance @balance+Amount end meth getBal(?B)B = @balanceend end class Customer attr name meth init(N)nameNend end class CustomerAccount from Customer Accountend A={New CustomerAccount init} C. Varela; Adapted from S. Haridi and P. Van Roy
Illegal inheritance class Account attr balance methinit(Amount) balance Amount end meth transfer(Amount) balance @balance+Amount end meth getBal(B)B = @balanceend end classCustomer attr name methinit(N) name Nend end classCustomerAccount from Customer Accountend There are two init methods visible for CustomerAccount This is illegal C. Varela; Adapted from S. Haridi and P. Van Roy
Legal inheritance class Account attr balance meth init(Amount)balance Amount end meth transfer(Amount)balance @balance+Amount end meth getBal(B)B = @balance end end class Customer attr name meth init(N) nameN end end class CustomerAccount from Customer Account meth init(N A) Customer,init(N) Account,init(A) end end CustomerAccount has attributes balance and name methods init, transfer and getBalance This overriding is not harmful: it does not change relationships in super classes C. Varela; Adapted from S. Haridi and P. Van Roy
Controlling visibility • Visibility is the control given to the user to limit access to members of a class (attributes, methods and features) • Each member is defined with a scope (part of program text that the member can be accessed by name) • Programming languages use words like public, private and protected to define visibility • Unfortunately different languages use these keywords to define different scopes C. Varela; Adapted from S. Haridi and P. Van Roy
Public and private scopes in ADTs • A private member is one which is only visible in the object instance (it is used for implementing the ADT) • The object instance can see all the private members in its class and its super classes • A public member is visible anywhere in the program • It is part of the interface of the ADT • In Oz (and Smalltalk) attributes are private and methods are public (the default rule) • In Java and C++ private has another meaning C. Varela; Adapted from S. Haridi and P. Van Roy
The meaning of Private C Class Hierarchy SubC SubSubC I1 I2 I3 I4 Instances C. Varela; Adapted from S. Haridi and P. Van Roy
The meaning of Private C Class Hierarchy According to Smalltalk and Oz SubC All private members in this region are visible to I3 SubSubC I1 I2 I3 I4 Instances C. Varela; Adapted from S. Haridi and P. Van Roy
The meaning of Private C Class Hierarchy According to C++ and Java All private members in this region are visible to I3 SubC SubSubC I1 I2 I3 I4 Instances C. Varela; Adapted from S. Haridi and P. Van Roy
Public and private scopes in ADTs • In Oz (and Smalltalk) attributes are private and methods are public • It is possible in Oz to make a method private within a class • Using a variable identifier as a method head will make the method local to the class • The variable is automatically bound to a unique name class C meth A(...) ... end .... end C. Varela; Adapted from S. Haridi and P. Van Roy
Public and private scopes in ADTs • In Oz (and Smalltalk) attributes are private and methods are public • It is possible in Oz to make a method private within a class • Using a variable identifier as a method head will make the method local to the class • The variable is automatically bound to a unique name • ! is an escape character, !A means escape the class scope class C meth A(...) ... end .... end local A = {NewName} in class C meth!A(...) ... end .... end end C. Varela; Adapted from S. Haridi and P. Van Roy
Programming techniques • First class messages (higher order programming) • Parameterized classes • Use of multiple inheritance C. Varela; Adapted from S. Haridi and P. Van Roy
Techniques of Higher order programming Control abstractions class HigherOrderControl meth forAll(ListObjects M) for O in ListObjects do {O M} end end ... end This technique allows messages as parameters C. Varela; Adapted from S. Haridi and P. Van Roy
Techniques of Higher order programming Control abstractions class HigherOrderControl ... meth nil skip end meth ’|’(M Ms) {self M} {self Ms} end end C = {New class $ from HigherOrderControl Counter end init(0)} {C [inc(2) display inc(3) display]} C. Varela; Adapted from S. Haridi and P. Van Roy
Parameterized classes • Classes are values like any other value • Therefore is it possible to define functions that return new classes as output fun {MakeClassAccountWithFee Fee} class $ %% Fee is in context environment fromAccount meth init(Amount) Account,init(Amount-Fee) end end end Account={MakeClassAccountWithFee 100} {New Account init(1000)} C. Varela; Adapted from S. Haridi and P. Van Roy
Classes as First Class Values fun {MakeClassAccountWithFee Fee} class $ %% Fee is in closure fromAccount meth init(Amount) Account,init(Amount-Fee) end end end Account={MakeClassAccountWithFee 100} {New Account init(1000)} C. Varela; Adapted from S. Haridi and P. Van Roy
Delegation and Forwarding Some object systems do not use inheritance (self) They use a notion known as delegation or forwarding Every class is an object Inheritance is implemented by forwarding messages the object cannot handle to a ”delegate” which behaves as a super-class Delegation preserves the ”self”, forwarding does not. C. Varela; Adapted from S. Haridi and P. Van Roy
Delegation example Account = {Newclass$ attr balance meth init balance := 0 end meth transfer(Amount) balance :=@balance+Amount end meth getBal(B)B = @balanceend end init} C. Varela; Adapted from S. Haridi and P. Van Roy
Delegation example (II) VerboseAccount = {New class $ from BaseObject attr delegate:Account meth verboseTransfer(Amount) {selftransfer(Amount)} {Browse {self getBal($)}} end meth otherwise(M) {@delegate M}end end init } By changing the delegate, the ”inheritance” hierarchy can be modified at run-time. C. Varela; Adapted from S. Haridi and P. Van Roy
Multiple inheritance • Multiple Inheritance is useful when an object has to be two different things in the same program (mixin inheritance) • Example, assume we have graphical objects • Line, circle, etc • Composite graphical objects (groups) • We use multiple inheritance to add the ability of grouping figures C. Varela; Adapted from S. Haridi and P. Van Roy
Class diagrams LinkedList Figure items init, add(O), forall(P) Line Circle CompositeFigure canvas x1, x2, y1, y2 canvas x, y, r init, move(X Y), display init, move(X Y), display init, move(X Y), display C. Varela; Adapted from S. Haridi and P. Van Roy