structure of programming languages oop. programming paradigm a way of conceptualizing what it means...
Post on 17-Jan-2016
218 Views
Preview:
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 basedFunctional : Equations; Expression Evaluation
Logical : First-order Logic DeductionObject-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, In contrast, Imperative programsImperative programs describe describe the details of the details of HOWHOW the results are to the results are to be obtained, in terms of the underlying be obtained, in terms of the underlying machine model.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 typeExternally 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 invocationsinitialization
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 memberfields 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 declaredblock 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 4method1: 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 4method1: x is 4method1: 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 4method1: x is 4method1: 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 4method1: x is 4method1: x is now 16main: 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 4method1: x is 4method1: x is now 16main: number is now 4
Variable Types
30
Static variablesdeclared within classassociated with class, not instance
Instance variablesdeclared within classassociated with instanceaccessible throughout object, lifetime of object
Local variablesdeclared within methodaccessible throughout method, lifetime of method
Parametersdeclared in parameter list of methodaccessible throughout method, lifetime of method
Static Fields/Methods
31
Static fields belong to whole classnonstatic fields belong to instantiated object
Static methods can only use static fieldsnonstatic methods can use either nonstatic or static
fieldsclass: 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 itselfas 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 variableuse "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 classaka class method
Do not have to instantiate object of class in order to invoke static method of that classCan use class name instead of object name to
invoke static methodcompiler will give error if static method
attempts to use nonstatic variableTherefore, 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 meanmain 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 classsay child's version overrides parent's version in
favor of its ownreminder: signature is number, type, and order of
parameters
Writing our own toString() method for class overrides existing, inherited toString() methodWhere 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 classObject class includes a toString() method
so... class header
public class myClassis actually same as
public class myClass extends Object
Overriding Variables
47
You can, but you shouldn'tPossible for child class to declare variable
with same name as variable inherited from parent classone in child class is called shadow variableconfuses everyone!
Child class already can gain access to inherited variable with same namethere'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 abstractNo 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 contracteven 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 typesAd-hoc Polymorphism Universal Polymorphism
Parametric (discussed with Functional Programming)Inclusion (discussed later in the lecture)
How to cater for Polymorphism
58
Coercion Overloading Parametric Inclusion
Polymorphism
Ad-Hoc Universal
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.
PolymorphismA polymorphic subroutine is one that can accept
arguments of different types for the same parametermax(x,y){ max = x>y?x:y } could be reused
for any type for which > is well-definedA 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
Fortranfunction rmax(x,y) real xreal yif (y .GT. x) rmax=yrmax=xreturnendIn k=rmax(i,j) causes args to be coerced to floating
point & return value truncated to integerAlthough 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 multiplicationp = a * q; // Scalar multiplicationx = y * z; // Matrix multiplication
Therefore overloading is good.
Recap: Shorthand Operators
63
Java shorthandcount++; // same as count = count + 1;count--; // same as count = count - 1;note no whitespace between variable name and
operatorSimilar 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" polymorphismin any class can use same name for several different (but
hopefully related) methodsmethods must have different signatures so that compiler
can tell which one is intendedMethod overriding: "complicated“ polymorphism
subclass has method with same signature as a method in the superclass
method in derived class overrides method in superclassresolved at execution time, not compilation time
some call it true polymorphism
Polymorphism(cont.)
C SC 520 Principles of Programming LanguagesLecture 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 maxmax(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; -- compatibleday := planet; -- type error
Polymorphism(cont.)
C SC 520 Principles of Programming LanguagesLecture 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
Adagenerictype T is private;with function “<=“(x, y : T) return Boolean;
function max(x,y : T) return T isbegin 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,”<=“);
top related