Structure of programming languages OOP. Programming Paradigm A way of conceptualizing what it means to perform computation and how tasks to be carried.

Slides:



Advertisements
Similar presentations
Object Oriented Programming
Advertisements

Object-Oriented Programming Python. OO Paradigm - Review Three Characteristics of OO Languages –Inheritance It isn’t necessary to build every class from.
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Abstract Data Types Data abstraction, or abstract data types, is a programming methodology where one defines not only the data structure to be used, but.
CS 211 Inheritance AAA.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance Inheritance Reserved word protected Reserved word super
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Mathematical Operations, Static Methods Lecture 9, Thu Feb 2.
ITEC200 – Week03 Inheritance and Class Hierarchies.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
INF 523Q Chapter 7: Inheritance. 2 Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Mathematical Operators, Static Methods Lecture 14,
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Static Methods, Conditionals Lecture 15, Mon Feb 8.
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.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
C++ fundamentals.
Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 Inheritance Inheritance is a fundamental object-oriented design technique used to.
Engr 691 Special Topics in Engineering Science Software Architecture Spring Semester 2004 Lecture Notes.
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
1 CS2104- ADT/Inheritance Lecturer: Dr. Abhik Roychoudhury School of Computing Reading : Chapter 7.1, 7.2 of textbook.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
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.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
CSE 501N Fall ‘09 14: Inheritance 20 October 2009 Nick Leidenfrost.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Programming in Java CSCI-2220 Object Oriented Programming.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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
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
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Object Oriented Programming
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Introduction to Object-Oriented Programming Lesson 2.
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.
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.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
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.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
Structure A Data structure is a collection of variable which can be same or different types. You can refer to a structure as a single variable, and to.
ISBN Chapter 12 Support for Object-Oriented Programming.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Structure of programming languages OOP. Inheritance.
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
Java Primer 1: Types, Classes and Operators
Chapter 3: Using Methods, Classes, and Objects
Inheritance Programming Language Design and Implementation
Inheritance Programming Language Design and Implementation
Java Programming Language
Inheritance Programming Language Design and Implementation
Inheritance Programming Language Design and Implementation
Presentation transcript:

Structure of programming languages OOP

Programming Paradigm A way of conceptualizing what it means to perform computation and how tasks to be carried out on the computer should be structured and organized. Imperative : Machine-model based Functional : Equations; Expression Evaluation Logical : First-order Logic Deduction Object-Oriented : Programming with Data Types

Imperative vs Non-Imperative Functional/Logic programs specify WHAT is to be computed abstractly, leaving the details of data organization and instruction sequencing to the interpreter. In contrast, Imperative programs describe In contrast, Imperative programs describe the details of HOW the results are to be obtained, in terms of the underlying machine model. the details of HOW the results are to be obtained, in terms of the underlying machine model.

Information hiding 4 We have no idea HOW an object is stored, nor do we care. All we care about is the behavior of the data according to the defined functions. Information hiding can be built into any language We will look at mechanisms later to enforce information hiding (Smalltalk, C++, Java, Ada). We will call this enforcement encapsulation

Information hiding -- C example: 5 typedef struct {i:int;... } TypeA; typedef struct {... } TypeB; P1 (TypeA X, other data) {... } - P1:other data  TypeA P2 (TypeB U, TypeA V) {... } - P2:TypeA  TypeB

Encapsulated data types-- Example: 6 StudentRecord is type Externally visible: void SetName(StudentRecord, Name) name GetName(StudentRecord) Internal to module: char Name[20]; float GPA; char Address[50]; CourseType Schedule[10];

Packages in ADA 7 package RationalNumber is type rational is record -- User defined type num, den: integer end record; procedure mult(x in rational; -- Abstract operation y in rational; z out rational); end package;

Packages in ADA 8 package body RationalNumber is -- Encapsulation procedure mult(x in rational; y in rational; z out rational) begin z.num := x.num * y.num; z.den := x.den * y.den; end; end package;

9 object is a collection of operations that share state. The object exists at run-time. A class is a textual description of the state variables ( fields ) and the operations ( methods ). A module is a syntactic mechanism for grouping related elements, and forms the basis for enforcing information hiding.

Introducing objects and classes into the Language 10 Class definition (via Inheritance) class variables (** not supported but can be easily incorporated **) instance variables (state) assignments (state changes) method definitions method invocations initialization Object creation (instantiation)

Additional Syntax 11 ( define the-grammar ’( (program ((arbno class-decl) expression) a-program)... (class-decl ("class" identifier "extends" identifier (arbno "field" identifier) (arbno method-decl) ) a-class-decl) (method-decl ("method" identifier "(" (separated-list identifier ",") ")" expression) a-method-decl) (expression ("new" identifier "(" (separated-list expression ",") ")") new-object-exp) (expression ("send" expression identifier "(" (separated-list expression ",") ")") method-app-exp) (expression ("super" identifier "(" (separated-list expression ",") ")") super-call-exp) ) )

Storage for C++ classes 12 Visibility of objects: public: globally known private: locally known only protected -- provides for inheritance

Scope 13 Fields of class are have class scope: accessible to any class member fields accessed by all class methods Parameters of method and any variables declared within body of method have local scope: accessible only to that method not to any other part of the code In general, scope of a variable is block of code within which it is declared block of code is defined by braces { }

Parameter Passing 14 Consider the following program: public class ParamTest1 { public static void main (String[] args) { int number = 4; System.out.println("main: number is " + number); method1(number); System.out.println("main: number is now " + number); } public static void method1(int x) { System.out.println("method1: x is " + x); x = x * x; System.out.println("method1: x is now " + x); }

Parameter Passing 15 Consider the following program: public class ParamTest1 { public static void main (String[] args) { int number = 4; System.out.println("main: number is " + number); method1(number); System.out.println("main: number is now " + number); } public static void method1(int x) { System.out.println("method1: x is " + x); x = x * x; System.out.println("method1: x is now " + x); } What's the flow of control?

Parameter Passing 16 Consider the following program: public class ParamTest1 { public static void main (String[] args) { 1 int number = 4; System.out.println("main: number is " + number); method1(number); System.out.println("main: number is now " + number); } public static void method1(int x) { System.out.println("method1: x is " + x); x = x * x; System.out.println("method1: x is now " + x); } What's the flow of control?

Parameter Passing 17 Consider the following program: public class ParamTest1 { public static void main (String[] args) { 1 int number = 4; 2 System.out.println("main: number is " + number); method1(number); System.out.println("main: number is now " + number); } public static void method1(int x) { System.out.println("method1: x is " + x); x = x * x; System.out.println("method1: x is now " + x); } What's the flow of control?

Parameter Passing 18 Consider the following program: public class ParamTest1 { public static void main (String[] args) { 1 int number = 4; 2 System.out.println("main: number is " + number); 3 method1(number); System.out.println("main: number is now " + number); } public static void method1(int x) { System.out.println("method1: x is " + x); x = x * x; System.out.println("method1: x is now " + x); } What's the flow of control?

Parameter Passing 19 Consider the following program: public class ParamTest1 { public static void main (String[] args) { 1 int number = 4; 2 System.out.println("main: number is " + number); 3 method1(number); System.out.println("main: number is now " + number); } public static void method1(int x) { 4 System.out.println("method1: x is " + x); x = x * x; System.out.println("method1: x is now " + x); } What's the flow of control?

Parameter Passing 20 Consider the following program: public class ParamTest1 { public static void main (String[] args) { 1 int number = 4; 2 System.out.println("main: number is " + number); 3 method1(number); System.out.println("main: number is now " + number); } public static void method1(int x) { 4 System.out.println("method1: x is " + x); 5 x = x * x; System.out.println("method1: x is now " + x); } What's the flow of control?

Parameter Passing 21 Consider the following program: public class ParamTest1 { public static void main (String[] args) { 1 int number = 4; 2 System.out.println("main: number is " + number); 3 method1(number); System.out.println("main: number is now " + number); } public static void method1(int x) { 4 System.out.println("method1: x is " + x); 5 x = x * x; 6 System.out.println("method1: x is now " + x); } What's the flow of control?

Parameter Passing 22 Consider the following program: public class ParamTest1 { public static void main (String[] args) { 1 int number = 4; 2 System.out.println("main: number is " + number); 3 method1(number); 7 System.out.println("main: number is now " + number); } public static void method1(int x) { 4 System.out.println("method1: x is " + x); 5 x = x * x; 6 System.out.println("method1: x is now " + x); } What's the flow of control?

Parameter Passing 23 Consider the following program: public class ParamTest1 { public static void main (String[] args) { 1 int number = 4; 2 System.out.println("main: number is " + number); 3 method1(number); 7 System.out.println("main: number is now " + number); } public static void method1(int x) { 4 System.out.println("method1: x is " + x); 5 x = x * x; 6 System.out.println("method1: x is now " + x); } What's printed?

Parameter Passing 24 Consider the following program: public class ParamTest1 { public static void main (String[] args) { 1 int number = 4; 2 System.out.println("main: number is " + number); 3 method1(number); 7 System.out.println("main: number is now " + number); } public static void method1(int x) { 4 System.out.println("method1: x is " + x); 5 x = x * x; 6 System.out.println("method1: x is now " + x); } What's printed? main: number is 4

Parameter Passing 25 Consider the following program: public class ParamTest1 { public static void main (String[] args) { 1 int number = 4; 2 System.out.println("main: number is " + number); 3 method1(number); 7 System.out.println("main: number is now " + number); } public static void method1(int x) { 4 System.out.println("method1: x is " + x); 5 x = x * x; 6 System.out.println("method1: x is now " + x); } What's printed? main: number is 4 method1: x is 4

Parameter Passing 26 Consider the following program: public class ParamTest1 { public static void main (String[] args) { 1 int number = 4; 2 System.out.println("main: number is " + number); 3 method1(number); 7 System.out.println("main: number is now " + number); } public static void method1(int x) { 4 System.out.println("method1: x is " + x); 5 x = x * x; 6 System.out.println("method1: x is now " + x); } What's printed? main: number is 4 method1: x is 4 method1: x is now 16

Parameter Passing 27 Consider the following program: public class ParamTest1 { public static void main (String[] args) { 1 int number = 4; 2 System.out.println("main: number is " + number); 3 method1(number); 7 System.out.println("main: number is now " + number); } public static void method1(int x) { 4 System.out.println("method1: x is " + x); 5 x = x * x; 6 System.out.println("method1: x is now " + x); } What's printed? main: number is 4 method1: x is 4 method1: x is now 16 ?????????????????????

Parameter Passing 28 Consider the following program: public class ParamTest1 { public static void main (String[] args) { 1 int number = 4; 2 System.out.println("main: number is " + number); 3 method1(number); 7 System.out.println("main: number is now " + number); } public static void method1(int x) { 4 System.out.println("method1: x is " + x); 5 x = x * x; 6 System.out.println("method1: x is now " + x); } What's printed? main: number is 4 method1: x is 4 method1: x is now 16 main: number is now 4

Parameter Passing 29 Consider the following program: public class ParamTest1 { public static void main (String[] args) { 1 int number = 4; 2 System.out.println("main: number is " + number); 3 method1(number); 7 System.out.println("main: number is now " + number); } public static void method1(int x) { 4 System.out.println("method1: x is " + x); 5 x = x * x; 6 System.out.println("method1: x is now " + x); } Why not 16? main: number is 4 method1: x is 4 method1: x is now 16 main: number is now 4

Variable Types 30 Static variables declared within class associated with class, not instance Instance variables declared within class associated with instance accessible throughout object, lifetime of object Local variables declared within method accessible throughout method, lifetime of method Parameters declared in parameter list of method accessible throughout method, lifetime of method

Static Fields/Methods 31 Static fields belong to whole class nonstatic fields belong to instantiated object Static methods can only use static fields nonstatic methods can use either nonstatic or static fields class: Giraffe getGiraffeCount() numGiraffes object: Giraffe1 sayHowTall() neckLength object: Giraffe2 sayHowTall() neckLength

Static Variables 32 public class Giraffe { private double neckLength; public Giraffe(double neckLength) { this.necklength = necklength; } public void sayHowTall() { System.out.println(“Neck is “ + neckLength); } how would we keep track of how many giraffes we’ve made? need a way to declare variable that "belongs" to class definition itself as opposed to variable included with every instance (object) of the class

Static Variables 33 public class Giraffe { private static int numGiraffes; private double neckLength; public Giraffe(double neckLength) { this.necklength = necklength; } public void sayHowTall() { System.out.println(“Neck is “ + neckLength); } static variable: variable shared among all instances of class aka class variable use "static" as modifier in variable declaration

Static Variables 34 public class Giraffe { private static int numGiraffes; private double neckLength; public Giraffe(double neckLength) { this.necklength = necklength; numGiraffes++; } public void sayHowTall() { System.out.println(“Neck is “ + neckLength); } updating static variable is straightforward increment in constructor

Static Variables 35 Static variable shared among all instances of class Only one copy of static variable for all objects of class Thus changing value of static variable in one object changes it for all others objects too! Memory space for a static variable established first time containing class is referenced in program

Static Methods 36 Static method "belongs" to the class itself not to objects that are instances of class aka class method Do not have to instantiate object of class in order to invoke static method of that class Can use class name instead of object name to invoke static method compiler will give error if static method attempts to use nonstatic variable Therefore, the main method can access only static or local variables.

Static Methods 37 public class Giraffe { private static int numGiraffes; private double neckLength; public Giraffe(double neckLength) { this.necklength = necklength; numGiraffes++; } public void sayHowTall() { System.out.println("Neck is " + neckLength); } public static int getGiraffeCount() { return numGiraffes; } static method example

Calling Static Method Example 38 public class UseGiraffes { public static void main (String[] args) { System.out.println("Total Giraffes: " + Giraffe.getGiraffeCount()); Giraffe fred = new Giraffe(200); Giraffe bobby = new Giraffe(220); Giraffe ethel = new Giraffe(190); Giraffe hortense = new Giraffe(250); System.out.println("Total Giraffes: " + Giraffe.getGiraffeCount()); } Note that Giraffe is class name, not object name! at first line haven’t created any Giraffe objects yet

Static Methods 39 public class UseGiraffes { public static void main (String[] args) { System.out.println("Total Giraffes: " + Giraffe.getGiraffeCount()); Giraffe fred = new Giraffe(200); Giraffe bobby = new Giraffe(220); Giraffe ethel = new Giraffe(190); Giraffe hortense = new Giraffe(250); System.out.println("Total Giraffes: " + Giraffe.getGiraffeCount()); } Now you know what all these words mean main method can access only static or local variables

Inheritance 40 Inheritance provides for passing information from one data object to another automatically It provides a form of data scope similar to syntactic scope. Inheritance through data in object oriented languages is explicit through derived types.

C++ derived classes 41 class complex: rational { public: void mult( complex x; complex y); { realpt.mult(x.realpt,y.realpt)- realpt.mult(x.imagpt,y.imagpt)... void initial(complex x) {x.realpt.num = 0; x.realpt.den = 1 }

C++ derived classes 42 // complex inherits rational components. private: rational realpt; rational imagpt }... complex M, N, P; M.mult(N,P)

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

Power of inheritance 44 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?)

Method Overriding 45 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 46 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 47 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 functions 48 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 49 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 50 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

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

Mixin inheritance 52 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 {... }

Abstract classes 53 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 54 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

Class Interfaces 55 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 56 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() {…} }

How to cater for Polymorphism 57 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 58 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 60 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 62 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 63 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;

Inclusion Polymorphism 64 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 65 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 66 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.

Method Overloading and Overriding 67 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

Polymorphism(cont.) C SC 520 Principles of Programming Languages Lecture Generic subroutines A generic subroutine is a syntactic template containing a type parameter that can be used to generate different code for each type instantiated Ada generic type T is private; with function “<=“(x, y : T) return Boolean; function max(x,y : T) return T is begin if x <= y then return y; else return x; end if; end min; function bool_max is new max(BOOLEAN,implies); function int_max is new max(INTEGER,”<=“);