Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Structure of programming languages OOP. Programming Paradigm A way of conceptualizing what it means to perform computation and how tasks to be carried."— Presentation transcript:

1 Structure of programming languages OOP

2 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

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

4 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

5 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

6 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];

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

24 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

25 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

26 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

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

28 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

29 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

30 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

31 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

32 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

33 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

34 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

35 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

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

37 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

38 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

39 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

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

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

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

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

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

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

46 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

47 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

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

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

50 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

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

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

53 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

54 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

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

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

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

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

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

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

61 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

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

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

64 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

65 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

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

67 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

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

69 Polymorphism(cont.) C SC 520 Principles of Programming Languages Lecture 04-69 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,”<=“);


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

Similar presentations


Ads by Google