Structure of programming languages OOP. Inheritance.

Slides:



Advertisements
Similar presentations
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Advertisements

C12, Polymorphism “many forms” (greek: poly = many, morphos = form)
Class Hierarchies. Inheritance is the capability of a class to use the properties and methods of another class while adding its own functionality. An.
Inheritance Inheritance Reserved word protected Reserved word super
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
PZ06A Programming Language design and Implementation -4th Edition Copyright©Prentice Hall, PZ06A - Inheritance Programming Language Design and Implementation.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Inheritance and Polymorphism Recitation – 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
Inheritance and Polymorphism CS351 – Programming Paradigms.
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
Engr 691 Special Topics in Engineering Science Software Architecture Spring Semester 2004 Lecture Notes.
1 CS2104- ADT/Inheritance Lecturer: Dr. Abhik Roychoudhury School of Computing Reading : Chapter 7.1, 7.2 of textbook.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
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.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
1 COSC3557: Object-Oriented Programming Haibin Zhu, Ph. D. Associate Professor of CS, Nipissing University.
CSE 501N Fall ‘09 14: Inheritance 20 October 2009 Nick Leidenfrost.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Chapter 12 Support for Object oriented Programming.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Inheritance Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section
Structure of programming languages OOP. Programming Paradigm A way of conceptualizing what it means to perform computation and how tasks to be carried.
Lecture 10 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Object-Oriented Programming Chapter Chapter
Csci 490 / Engr 596 Special Topics / Special Projects Software Design and Scala Programming Spring Semester 2010 Lecture Notes.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Object Oriented Programming
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Coming up: Inheritance
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
CSCI-383 Object-Oriented Programming & Design Lecture 24.
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.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
OOP Basics Classes & Methods (c) IDMS/SQL News
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
CSCI-383 Object-Oriented Programming & Design Lecture 17.
ISBN Chapter 12 Support for Object-Oriented Programming.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
7. Inheritance and Polymorphism
Inheritance and Polymorphism
Polymorphism.
Types of Programming Languages
Inheritance Programming Language Design and Implementation
Java Programming Language
Week 6 Object-Oriented Programming (2): Polymorphism
Java Inheritance.
Inheritance Programming Language Design and Implementation
Lecture 10 Concepts of Programming Languages
Inheritance Programming Language Design and Implementation
Inheritance Programming Language Design and Implementation
Programming in C# CHAPTER 5 & 6
Presentation transcript:

Structure of programming languages OOP

Inheritance

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

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

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?)

Override

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?

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

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

Virtual Function

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.

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.

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

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

Virtual Functions (cont’d)

Mixin inheritance

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

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 {... }

Class Hierarchy is a DAG

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 { /*... */ };

Operator Overloading

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. 

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

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

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.).

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

Abstract Class

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

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

Interface

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!

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 Bunnies and Interfaces public interface Bunnies { public void moveBunny(int direction); }

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 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 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 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"); }

Polymorphism

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)

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.

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.

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;...

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

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.

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;

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

Polymorphism(cont.) C SC 520 Principles of Programming Languages Lecture 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

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

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

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.

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(); }

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 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 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 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() {...}; };