Presentation is loading. Please wait.

Presentation is loading. Please wait.

Structure of programming languages OOP. Inheritance.

Similar presentations


Presentation on theme: "Structure of programming languages OOP. Inheritance."— Presentation transcript:

1 Structure of programming languages OOP

2 Inheritance

3 3 Inheritance provides for passing information from one data object to another automatically Inheritance through data in object oriented languages is explicit through derived types.

4 4 Inheritance Allows new classes defined in terms of existing ones, i.e., by inheriting common parts Can be complicated by access controls to encapsulated entities A class can hide entities from its subclasses (private) A class can hide entities from its clients A class can also hide entities for its clients while allowing its subclasses to see them A class can modify an inherited method The new one overrides the inherited one The method in the parent is overridden

5 Power of inheritance 5 class rational { public: mult(...) {... } protected: error(...) {... }... private:... } class complex:rational { public: mult(...) {... } private:... } complex X;

6 Power of inheritance 6 Function error is passed (inherited) to class complex, so X.error is a valid function call. Any derived class can invoke error and a legal function will be executed. But what if we want error to print out the type of its argument? (i.e., want to know if error occurred in a rational or complex data?)

7 Override

8 Method Overriding 8 If child class defines method with same name and signature as method in parent class say child's version overrides parent's version in favor of its own reminder: signature is number, type, and order of parameters Writing our own toString() method for class overrides existing, inherited toString() method Where was it inherited from?

9 Method Overriding 9 Where was it inherited from? All classes that aren't explicitly extended from a named class are by default extended from Object class Object class includes a toString() method so... class header public class myClass is actually same as public class myClass extends Object

10 Overriding Variables 10 You can, but you shouldn't Possible for child class to declare variable with same name as variable inherited from parent class one in child class is called shadow variable confuses everyone! Child class already can gain access to inherited variable with same name there's no good reason to declare new variable with the same name

11 Virtual Function

12 Virtual functions 12 Base class: class rational { error() { cout << name() << endl; } string name() { return “Rational”;}... } Derived class: class complex: rational { string name() { return “Complex”;}... } But if error is called, Rational is always printed since the call rational::name is compiled into class rational for the call in the error function.

13 Virtual functions 13 But if name is defined as: virtual string name() { return “Rational”;} then name() is defined as a virtual function and the function name in the current object is invoked when name() is called in rational::error.

14 Implementing virtual functions 14 Virtual functions imply a runtime descriptor with a location of object rational A; complex B; A.error()  error will call name() in rational B.error()  error will call name() in complex

15 Virtual Functions Allow print in both employee and manager, with different definitions. C++ will “do the right thing”, based on the actual object class.

16 Virtual Functions (cont’d)

17

18

19 Mixin inheritance

20 20 Assume want to add feature X to both class A and B: Usual way is to redefine both classes.

21 Mixin inheritance 21 Mixin inheritance: Have definition which is addition to base class (Not part of C++) For example, the following is possible syntax: featureX mixin {int valcounter}  Add field to object newclassA class A mod featureX; newclassB class B mod featureX; Can get similar effect with multiple inheritance: class newclassA:A,featureX {... } class newclassB:B,featureX {... }

22 Class Hierarchy is a DAG

23 Class Hierarchies class employee { /*... */ }; class manager: public employee { /*... */ }; class director: public manager { /*... */ }; class temporary { /*... */ }; class secretary: public employee { { /*... */ }; class tsec: public temporary, //MULTIPLE INHERITANCE !! public secretary { /*... */ }; class consultant: public temporary, public manager { /*... */ };

24 Operator Overloading

25 Allow intrinsic operators in C++ to be applied to objects of new types. Overloading is achieved by defining functions named operatorXXX, where XXX is one of: Can’t overload these: Can’t change precedence, arity or associativity. Can’t add new operators, either. 

26 Operator Overloading (cont’d) Example: the subscript operator, which returns a reference. First, without operator overloading:

27 Operator Overloading (cont’d) Now, simply replace elem with operator[]:

28 Overloading Operators > We wish to use > for user-defined objects, the same way they are (normally) used for "built-in" objects (e.g. int, char, etc.).

29 Overloading Operators > Input is similar. The signature is: To use them:

30 Abstract Class

31 Abstract classes 31 A class C might be abstract No instance of C can be created. But instances of subclasses of C can be created. Useful to capture the commonality shared by a set of classes. Expression binary Var. Value

32 Abstract clases 32 abstract class Expression { … } class Binary extends Expression {…} class Variable extends Expression { … } class Value extends Expression { … } In an abstract class Some of the methods are defined inside the abstract class Rest of the methods defined via the subclasses

33 Interface

34 Class Interfaces 34 Typically, identifies a collection of methods to be implemented by various classes. All methods are “abstract” : not defined in the interface. Concrete methods are implemented in the classes implementing the interface. All methods must be implemented in such class definitions. Can write code that works on anything that fulfills contract even classes that don’t exist yet!

35 Class Interfaces 35 Public abstract interface Enumeration { // the method signatures appear here public abstract boolean hasMoreElements(); public abstract object nextElement (); } Public class stringTok extends Object implements Enumeration{ // the method implementations appear here public boolean hasMoreElements() {…} public Object nextElement() {…} }

36 36 Bunnies and Interfaces public interface Bunnies { public void moveBunny(int direction); }

37 37 Bunnies and Interfaces public class BigBunny implements Bunnies { private int x, y; private int carrots; public BigBunny() { x = 5; y = 5; carrots = 10; } public void moveBunny(int direction) { if (direction == 12) { y = y + 3; carrots = carrots - 2; }

38 38 Bunnies and Interfaces else if (direction == 3) { x = x + 3; carrots = carrots - 2; } else if (direction == 6) { y = y - 3; carrots = carrots - 2; } else if (direction == 9) { x = x - 3; carrots = carrots - 2; } else { System.out.println("Invalid direction"); }

39 39 Bunnies and Interfaces public class LittleBunny implements Bunnies { private int x, y; private int carrots; public LittleBunny() { x = 5; y = 5; carrots = 10; } public void moveBunny(int direction) { if (direction == 12) { y = y + 1; carrots = carrots - 1; }

40 40 Bunnies and Interfaces else if (direction == 3) { x = x + 1; carrots = carrots - 1; } else if (direction == 6) { y = y - 1; carrots = carrots - 1; } else if (direction == 9) { x = x - 1; carrots = carrots - 1; } else { System.out.println("Invalid direction"); }

41 Polymorphism

42 How to cater for Polymorphism 42 Polymorphism = poly (many) + morph (form) Polymorphism is the ability of a data object to that can take on or assume many different forms. Polymorphism can be categorized into 2 types Ad-hoc Polymorphism Universal Polymorphism Parametric (discussed with Functional Programming) Inclusion (discussed later in the lecture)

43 How to cater for Polymorphism 43 CoercionOverloadingParametricInclusion Polymorphism Ad-HocUniversal Ad-Hoc polymorphism is obtained when a function works, or appears to work on several different types (which may not exhibit a common structure) and may behave in unrelated ways for each type. Universal polymorphism is obtained when a function works uniformly on a range of types; these types normally exhibit some common structure.

44 Polymorphism A polymorphic subroutine is one that can accept arguments of different types for the same parameter max(x,y){ max = x>y?x:y } could be reused for any type for which > is well-defined A polymorphic variable(parameter) is one that can refer to objects of multiple types. ML: x : ‘a True (or “pure”) polymorphism always implies code reuse: the same code is used for arguments of different types.

45 Polymorphism – Coercion 45 A coercion is an operation that converts the type of an expression to another type. It is done automatically by the language compiler. (If the programmer manually forces a type conversion, it’s called casting) E : int E : float (Int-Float Coercion) int x; float y;... y := x;...

46 Polymorphism(cont.) Coerced subroutine arguments A coercion is a built-in compiler conversion from one type to another Fortran function rmax(x,y) real x real y if (y.GT. x) rmax=y rmax=x return end In k=rmax(i,j) causes args to be coerced to floating point & return value truncated to integer Although same code is used for both arg types, this is not true polymorphism

47 Polymorphism – Overloading 47 Overloading (+) Increase flexibility in programming Examples are when user wants to use an operator to express similar ideas. Example: int a,b,c; int p[10], q[10], r[10]; int x[10][10], y[10][10], z[10][10]; a = b * c; // integer multiplication p = a * q; // Scalar multiplication x = y * z; // Matrix multiplication Therefore overloading is good.

48 Recap: Shorthand Operators 48 Java shorthand count++; // same as count = count + 1; count--; // same as count = count - 1; note no whitespace between variable name and operator Similar shorthand for assignment tigers += 5; // like tigers=tigers+5; lions -= 3; // like lions=lions-3; bunnies *= 2; // like bunnies=bunnies*2; dinos /= 100; // like dinos=dinos/100;

49 Method Overloading and Overriding 49 Method overloading: "easy" polymorphism in any class can use same name for several different (but hopefully related) methods methods must have different signatures so that compiler can tell which one is intended Method overriding: "complicated“ polymorphism subclass has method with same signature as a method in the superclass method in derived class overrides method in superclass resolved at execution time, not compilation time some call it true polymorphism

50 Polymorphism(cont.) C SC 520 Principles of Programming Languages Lecture 04-50 Overloading An overloaded name refers to several distinct objects in the same scope; the name’s reference (denotation) is resolved by context. Unfortunately sometimes called “ad hoc polymorphism”(!) C++ int j,k; float r,s; int max(int x, int y){ return x<=y?y:x } float max(float x, float y){ return y>x?y:x } … max(j,k);// uses int max max(r,s);// uses float max Even constants can be overloaded in Ada: type weekday is (sun, mon, …); type solar is (sun, merc, venus, …); planet: solar; day: weekday; day := sun; planet := sun;-- compatible day := planet;-- type error

51 Inclusion Polymorphism 51 Q: Is the subclass regarded as a subtype of the parent class? Yes – Inclusion Polymorphism (Sub-typing) class A {…} class B extends A {…} Note that B  A (Inclusion) A a = new B(); A a = new A(); Polymorphism

52 Inclusion Polymorphism 52 Q: Is the subclass regarded as a subtype of the parent class? Yes – Inclusion Polymorphism (Sub-typing)  Some people call it the IS-A relationship between parent and derived class.  “class Table extends Furniture”  Table IS-A Furniture.  Table  Furniture

53 Inclusion Polymorphism 53 Variables are polymorphic – since they can refer to the declared class and to subclasses too. Requirement (Do you know why?): Subclass must INHERIT EVERYTHING from the base class. Subclass must NOT MODIFY ACCESS CONTROL of the base class methods/data. That’s why C++ Inclusion Polymorphism definition adds a ‘public’ to the derived class since a private derived class modifies access control of base class methods/data.

54 Scoping: Lexical vs Static class A { static int cv; int iv; } class Test { public static void main(String [] args){ int iv, cv; class B extends A { void print() { System.out.print( “”+ cv + iv ); /*error*/ System.out.println( “”+ this.cv + this.iv ); } new B(). print(); }

55 Binding: Dynamic vs Static class A { static int cv = 10; int iv = 70; int f() {return 40;} void print() { System.out.println( “”+ cv + iv + f()); }} class B extends A { static int cv = 33 ; int iv = 88; int f() {return 55;} } class Test2 { public static void main(String [] args){ new A(). print(); new B(). print(); }}

56 56 Dynamic Binding A polymorphic variable can be defined in a class that is able to reference (or point to) objects of the class and objects of any of its descendants Shape *shape_list[3]; // array of shapes shape_list[0] = new Circle; shape_list[1] = new Square; shape_list[2] = new Triangle; for(int i = 0; i < 3; i++){ shape_list[i].draw(); }

57 57 Dynamic Binding When a class hierarchy includes classes that override methods and such methods are called through a polymorphic variable, the binding to the correct method will be dynamic, e.g., shape_list[i].draw(); Allows software systems to be more easily extended during both development and maintenance, e.g., new shape classes are defined later

58 58 Dynamic Binding (cont.) An abstract method is one that does not include a definition (it only defines a protocol) An abstract class is one that includes at least one virtual method An abstract class cannot be instantiated class Shape { private: int x; int y; public:... virtual void draw(); }; class Circle: public Shape { private: int radius; public:... void draw() {...}; };


Download ppt "Structure of programming languages OOP. Inheritance."

Similar presentations


Ads by Google