licence mention informatique – l2/s4 – 2013 …wolff/teach-material/2014-15/l2...licence mention...

51
Licence Mention Informatique – L2/S4 – 2013 Programmation Object & Genie Logiciel Burkhart Wolff Département Informatique

Upload: ngonhi

Post on 27-Jun-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

Licence Mention Informatique – L2/S4 – 2013Programmation Object

&Genie Logiciel

Burkhart WolffDépartement Informatique

2013 B. Wolff, L2-PO&GL, Introduction 2

But du cours

Introduction à la programmation avancé en Java

(programming „in the small“,concepts du language et techniques de base pour construire des programmes 50000 loc)

Introduction au Genie Logiciel

(programming „in the large“,concepts des processus de développement,de la spécification et d'analyse,techniques de base pour construire des programmes 50 M loc)

2013 B. Wolff, L2-PO&GL, Introduction 3

Mise en œuvre associée

9 cours, (vendredi )

10 TD,

5 TP,

Contrôle des connaissances 1 partiel + 1 examen final

Page WEB avec tous les slides, exercises, liensbibliographiques, infos ...

http://www.lri.fr/ ~wolff/teach-material/2012-13/L2-POnGL/index.html

2013 B. Wolff, L2-PO&GL, Introduction 4

Mise en œuvre associée

L2 - Course: Programmation Objet-orienté et Genie Logiciel

Cours:

C1 - 21.1, 15:45 - 17:30, [336-112]: Welcome, Intro, Java-Reminder, and Details on Dynamic TypingC2 - 1.2, 11:15 - 13:00, [336-112]: Inheritance, Overriding and OverloadingC3 - 8.2, 11:15 - 13:00, [336-112]: ExceptionsC4 - 15.2, 11:15 - 13:00, [336-112]: Generics in OO Languages (F.Voisin)C5 - 22.2, 11:15 - 13:00, [336-112]: Design-Patterns, Introduction GLC6 - 22.3, 11:15 - 13:00, [336-112] Components of UML Using UML in AnalysisC7 - 29.3, 11:15 - 13:00, [336-112] Using UML in DesignC8 - 5.4, 11:15 - 13:00, [336-112]: Introduction to TestingC9 - 12.4., 11:15 - 13:00, [336-112]Partiel: ??? <<11:40), Bat 336, no 173-212 Examen: ??? Examen(2ieme sess): ???

Planning détaillé TD et TP sera annoncé !!!

2013 B. Wolff, L2-PO&GL, Introduction 5

Overview

What is Object-Orientation ?

A Gentle Review of Java (Concepts and Syntax) Types Control-structures Methods Classes Programs

Compléments (1) Inheritance and Casting

2013 B. Wolff, L2-PO&GL, Introduction 6

Overview

What is Object-Orientation ?

A Gentle Review of Java (Concepts and Syntax) Types Control-structures Methods Classes Programs

Compléments (1) Inheritance and Casting

2013 B. Wolff, L2-PO&GL, Introduction 7

What is OO?

OO ... ... is „a particular, data-oriented view“ for modeling (see UML) and programming [instead of imperative programming, that tries to put instructions into the center of universe, or functional programming, that is centered around the idea of „functions are first class citizens“.] ... is trying to map „objects of the real world“ to data entities (=objects) of a system ... puts emphasis on data-encapsulation and interfaces turning components of a program or a model exchangeable ... lets objects have

an identity attributes (fields) a dynamic and (in modern languages) a static type.

2013 B. Wolff, L2-PO&GL, Introduction 8

What is OO?

Objects ... ... are a piece of encapsulated memory. They have in general a mutable state ... have

an identity attributes (fields) which can be identities (references) of other objects (creating „object graphs“), a dynamic and (in modern languages) a static type, (or in other words: actual type vs. apparent type)

and viewed in context of a module: a class, which can be organized into families via sub-typing and inheritance.

Objects can be implemented in any (nearly) any language !!!

2013 B. Wolff, L2-PO&GL, Introduction 9

A Hierarchy od Variants

Point

x, y: float

shift(dx, dy: float)

Figures Origin: Point : Point bool area: float move_at(…) rotate(…)

Circle Rayon: float

: Point bool area: float rotate(…)

Rectangle largeur, longueur: float

: Point bool area: float rotate(…)

Triangle Side: float A1, A2: radian

: bool Aire: float rotate(…)

Square …

Not a perfect example ....

2013 B. Wolff, L2-PO&GL, Introduction 10

History of OOP

OO became popular since the early 80ies, but there is a long story of predecessors [Simula 1967]

they are not a panacea (Conception ? Test ? Correctness?)

not a concensus on all features ? typed (Ada95, C++, Eiffel, Java, C#) or not typed (Smalltalk) ? simple inheritance (Ada95, Java, C#) or multiple inh. (C++) ? static (C++, C# by default) or dynamic binding (Java) of methods?

Or both (C++, C#, Ada95) ? Classes: static (C++, Ada) ou dynamic (Java, C#) ? « 100% object»(Eiffel, C#) or “object oriented”(Java,C++,Ada,C#) Interfaces or abstract classes ? Packages ? Generics or not (Java ? C++ ? C# ? F# ? Scala ?)

2013 B. Wolff, L2-PO&GL, Introduction 11

Links ...

Procedural Langages Hybrid Langages Functional Langages

Algol (60)

Simula (67)

Pascal (74)C (~70)

Ada(83)

Ada(95)

Eiffel (85)

C++ (~80)

Java(~95) C# (~98)

F# (2002)

Scala (2001)

LISP (60)

Smalltalk(74/80/85)

Self (90)

CLOS (81)

ML (~80), SML, CAML (~90)HASKELL,…

Not considered: ParallelismScripting LanguagesLogical prog. PROLOG…

Scheme (~70)

objC (~85)

2013 B. Wolff, L2-PO&GL, Introduction 12

Overview

What is Object-Orientation ?

A Gentle Review of Java (Concepts and Syntax) Types Control-structures Methods Classes Programs

Compléments (1) Inheritance and Casting

2013 B. Wolff, L2-PO&GL, Introduction 13

Review: Types (1)

Java is a (statically) typed language. So it has:

Types for Built-in Operations

Class-Types (i.e. Types resulting from a Class declaration

2013 B. Wolff, L2-PO&GL, Introduction 14

Review: Types (2)

Base Types Name Constants Common Operators

booleans boolean true false && (and) || (or) ! (not)integers int 132 -67 3e8 - (unary,bin.) + * /

% (modulo) - - ++ > >= < <= ==(equality) !=

bytes byte -32 0xA8 - + * / % - - ++ > >= < <= == !=

short ints short 252 756 - + * / % - - ++ > >= < <= == !=

long ints long -2544L 75443L - + * / % - - ++ > >= < <= == !=

simp. prec. float 8,42f -6,63e-4f - + * / > >= < <= == !=

doub. prec. double 2.23 -4.32e-12 - + * / > >= < <= == !=

Unicode char ’a’ ’Z’\0xABCE > >= < <= == !=

2013 B. Wolff, L2-PO&GL, Introduction 15

Variables (1)

Java has imperative features, i.e. (program) variables.Declaration: <type> <identifier> [= <expr>];

where <expr> is the initialisation valueExamples:

int myInt ; // default value : 0double myFloat = 2.212 ;char myChar = ’a’ ;

Assignment: <variable> = <expression> ;Examples:

myInt = 8 ;

Variants : += -= etc. (as in CC++)

2013 B. Wolff, L2-PO&GL, Introduction 16

Variables (2)

Another form of Program Variables are Array Variables:

Declaration : <type>[] <identifer> [=<elt0>, <elt1>,...];where <elti> are constants.

Examples: int[] myArray ;double[] myArray2 = {3.12, 4.11, 8.3};double[][] myMatrix = new double[3][3] ;myMatrix[1][2]=12 ; // line 1 , colon 2

Allocation: <array> = new <type>[<size>] ;Example: myArray = new int[20] ;

Assignment: <array>[<index>] = <expression> ;Example: myArray[5] = 8 ;

2013 B. Wolff, L2-PO&GL, Introduction 17

Variables (3)

Another form of Program Variables are Array Variables(ctd):

Acces : <tableau>[<index>]

Example: System.out.println(monTableau[5]) ;// Note : The <index> range from 0 to <size>-1.// Arrays have fixed size.myArray2[4]=1.5 ; // will raise an exception

ArrayOutOfBoundsException

Size: <tableau>.lengthExample: System.out.println("size = "+

ayArray.length);

2013 B. Wolff, L2-PO&GL, Introduction 18

Variables(4)

A (dynamic, resizable) variant of arrays :

Import: import java.util.ArrayList;

Declaration:ArrayList<type objet> <name tabdyn>;Example: ArrayList<Integer> myTab;

ArrayList<String> myTab2;

Allocation: <tabdyn> = new ArrayList<type>();Example: myTab2 = new ArrayList<String>();

Add: <tabdyn>.add(<expression>) ;Example: myTab.add(8) ;

myTab2.add("penguin") ;

2013 B. Wolff, L2-PO&GL, Introduction 19

Variables(5)

A (dynamic, resizable) variant of arrays :

Array Access: <tabdyn>.get(<integerindex>)Example: System.out.println(myTab.get(0)) ;

// Note : The <index> range from 0 to <size>-1.myTab.get(5) ; // raises an exception

IndexOutOfBoundsException

Size: <tabdyn>.size()

Example: System.out.println("size =“ +myTabdyn.size());

2013 B. Wolff, L2-PO&GL, Introduction 20

Variables(6)

Non-mutable Strings:

Import: import java.lang.String(redundant: all under java.lang is automatically imported)

Declaration: String myString="This is a nice string" ;

Size: myString.length()

Comparison: myString.equals(anotherString)

Mutable Strings:

Import : java.lang.StringBuffer

2013 B. Wolff, L2-PO&GL, Introduction 21

Input and Output:

Standard Output:

System.out.print("Hello") ; // without carriage return System.out.println(" world "+2+" !") ;

// with carriage return

Output on Standard-Error:

System.err.println("Problem !") ;

Standard Input

System.in.read() // reads char as int, and gives -1 for EOF

2013 B. Wolff, L2-PO&GL, Introduction 22

Visibility of Declarations

Local Variables, Parameters and Local Declarations follow the block-structure of Java-Programs:

public void method(int a, int b) {int c = a + b;if (c+a>b) {

int a = 2*a-b; c = a+b; } else { long b = 8; c = a + b; } }

b

a

ca b

2013 B. Wolff, L2-PO&GL, Introduction 23

Control Structures(1)

Conditional:

Syntax : if(<condition>) <command> [ else <command> ]

Note : <command> can be an instruction <instr> ;or a bloc { <instr1> ; <instr2> ; ... }.

Example: if (i>12)System.out.print("large ");

else{int a = 8; int b = 9; System.out.println("small ");}

System.out.println(i);

2013 B. Wolff, L2-PO&GL, Introduction 24

Control Structures(2)

Case-Distinction:

Syntax: switch(<expr>) {case <value-1> : <command-1> ; break ;case <value-2> : <command-2> ; break ;...default : <command-D> ;}

where <expr> is of type int char byte short

If <expr> has <value-i>, the <command-i> is executed. If none matches, the default <command-D> is executed.

2013 B. Wolff, L2-PO&GL, Introduction 25

Control Structures(3)

Case-Distinction:

Example:int myInt = 1;String str = "";switch(myInt) {

case 0 : str="zero"; break;case 1 : str="one"; break;case 2 : str="two"; break;default : str="rather large";

}System.out.println(myInt+" is "+str);

2013 B. Wolff, L2-PO&GL, Introduction 26

Control Structures (4)

While - Loop:

Syntax : while(<condition>) <command> or

do <command> while(<condition>)

Note : <command> can be an instruction <instr> ;or a bloc { <instr1> ; <instr2> ; ... }.

Example: int i = 0;// we assume an array tab while(i<tab.length)

System.out.println(tab[i++]);

2013 B. Wolff, L2-PO&GL, Introduction 27

Control Structures (5)

General Iterator Loop (since Java 1.5):

Syntax : for(<class-type> <variable>:<collection>) <command>

Note : <command> can be an instruction <instr> ;or a bloc { <instr1> ; <instr2> ; ... } and<collection> can is an <expr> of type ArrayList,HashSet, etc.

Example: int siz = 0;// we assume an array tab for(Object obj : tab) {

System.out.println(„Elem:“ + obj);siz++;

}

2013 B. Wolff, L2-PO&GL, Introduction 28

Control Structures (6)

Control of Exceptions:

Syntax : try <commands> catch(Exception-1 <var>) <commands-1> ... catch(Exception-n <var>) <commands-n>

Example: try { // let tabdyn dyn.array and nb for(int i=0;i<nb;i++)

System.out.println(tabdyn.get(i)); // throws IndexOutOfBoundsException

} catch(IndexOutOfBoundsException e) {System.err.println("out of bound: "+nb);e.printStackTrace(System.err); // produces stacktraceSystem.exit(1); // erroneous prog. exit

}

2013 B. Wolff, L2-PO&GL, Introduction 29

Methods (1)

Method declarations (in the context of class declarations):

Syntax : <modifier> <type> <methodname>( <argument-list> ) { <command> }

Note: <modifier> can be public, private, static, ... <argument-list> can be empty.

Example: public double calculateAnswer(double wingSpan,

int numberOfEngines, double length, double grossTons)

{//do the calculation here

}

2013 B. Wolff, L2-PO&GL, Introduction 30

Methods (2)

Method - invocations:

Syntax : <expr>.<methodname>(<expr-list>)

Note: Semantics complicated. To be discussed later.In general, the “dynamic type” of the first argument(before the “.”, internally referenced by “this”) decides what method - body alongthe class hierarchy is chosen and executed(exception: static methods.)

2013 B. Wolff, L2-PO&GL, Introduction 31

Class Declarations (1)

Class Declarations

Syntax : class <class-name> { // field, constructor,

// and method declarations}class <class-name> extends <sup-class-name>

// field, constructor, // and method declarations}

Note: field declarations consist of an optional <modifier> and a variable declaration (as seen before).

Note: a further syntactic option allows the use of interfaces (to be discussed later).

2013 B. Wolff, L2-PO&GL, Introduction 32

A Program in Java

Let the file matrices/MatricesMain.java be: package matrices; public class MatricesMain {

public static void main(String[] args) { double x = 0.0; try { x = Double.parseDouble(args[0]); } catch(NumberFormatException e) { System.out.println("Syntaxe:MatricesMain <x> with <x> double"); System.exit(1); }

double[][] mat1 = { { 1,2,3 }, { 4,5,6 }, { 7,8,9 } }; Matrices.print(mat1); System.out.println("* "+x); System.out.println("="); double[][] mat2 = Matrices.mul(x,mat1); Matrices.print(mat2);}

}

Compilation: javac matrices/* Execution: java matrices.MatricesMain

2013 B. Wolff, L2-PO&GL, Introduction 33

Overview

What is Object-Orientation ?

A Gentle Review of Java (Concepts and Syntax) Types Control-structures Methods Classes Programs

Complements (1) Inheritance and Casting

2013 B. Wolff, L2-PO&GL, Introduction 34

Complements: Static and Dynamic Types

Classes induce class types which are organized along the inheritance hierarchy in form of corresponding subtypes The top element in the hierarchy is the type Object Subtypes can be inferred „statically“ in Java by the type-checker (inside the java compiler) Object instances have an „internal marker“, which keeps track of the type has when it was dynamically created: the dynamic type (= actual type). The interplay of static (apparent) and dynamic (actual) types becomes visible when

casting objects (<type>) <expr> testing dynamic types <expr> instanceof <type>

2013 B. Wolff, L2-PO&GL, Introduction 35

Static and Dynamic Types

Example

public class MainClass {   public static void main(String[] a) {     String s = null;     if (s instanceof java.lang.String) {       System.out.println("true");     } else {      System.out.println("false");     }   } }

Running this program yields what ?

2013 B. Wolff, L2-PO&GL, Introduction 36

Static and Dynamic Types

Example

public class MainClass {   public static void main(String[] a) {     String s = null;     if (s instanceof java.lang.String) {       System.out.println("true");     } else {      System.out.println("false");     }   } }

Running this program yields what ? false. Null is a special case.

2013 B. Wolff, L2-PO&GL, Introduction 37

Static and Dynamic Types

Example

class Parent {  public Parent() {} }

class Child1 extends Parent {  public Child1() {    super();   } }

class Child2 extends Parent {  public Child2() {    super();  }

2013 B. Wolff, L2-PO&GL, Introduction 38

Static and Dynamic Types

Example (ctd):

class Grandson extends Child2 {  public Grandson() {    super();  } } public class MainClass {  public static void main(String[] a) {    Child1 child = new Child1();    if (child instanceof Parent) {      System.out.println("true");    } }  }

Running this program yields what ?

2013 B. Wolff, L2-PO&GL, Introduction 39

Static and Dynamic Types

Example (ctd):

class Grandson extends Child2 {  public Grandson() {    super();  }

public class MainClass {  public static void main(String[] a) {    Child1 child = new Child1();    if (child instanceof Parent) {      System.out.println("true");    }

  }

Running this program yields what ? true.

2013 B. Wolff, L2-PO&GL, Introduction 40

Static and Dynamic Types

Actually, when representing the previous example ina class diagram of the UnifiedModelling Language, it lookslike this …

Above all, there is the supertypeObject which we omit here ...

Parent

Child1

Child2

Grandson

F

2013 B. Wolff, L2-PO&GL, Introduction 41

Static and Dynamic Types

Casting in a class hierarchy:

Syntax: (<type>)<expr> We assume to have created

objects:

a::Parent,b::Child1,c::Child2, d::Grandson,f::F

where <expr> :: <type> isa notation (NOT Java) for„expr e has static type T“.

Parent

Child1

Child2

Grandson

F

2013 B. Wolff, L2-PO&GL, Introduction 42

Static and Dynamic Types

Casting in a class hierarchy:

Syntax: (<type>)<expr> We assume to have created

objects:

a::Parent,b::Child1,c::Child2, d::Grandson,f::F

What is:

(F) b ?(Parent) b ?(Parent) d ?(Child1) a ?

Parent

Child1

Child2

Grandson

F

2013 B. Wolff, L2-PO&GL, Introduction 43

Static and Dynamic Types

Casting in a class hierarchy:

Syntax: (<type>)<expr> We assume to have created

objects:

a::Parent,b::Child1,c::Child2, d::Grandson,f::F

What is:

(F) b ill-typed!(Parent) b ?(Parent) d ?(Child1) a ?

Parent

Child1

Child2

Grandson

F

2013 B. Wolff, L2-PO&GL, Introduction 44

Static and Dynamic Types

Casting in a class hierarchy:

Syntax: (<type>)<expr> We assume to have created

objects:

a::Parent,b::Child1,c::Child2, d::Grandson,f::F

What is:

(F) b ill-typed!(Parent) b ::Parent(Parent) d ?(Child1) a ?

Parent

Child1

Child2

Grandson

F

2013 B. Wolff, L2-PO&GL, Introduction 45

Static and Dynamic Types

Casting in a class hierarchy:

Syntax: (<type>)<expr> We assume to have created

objects:

a::Parent,b::Child1,c::Child2, d::Grandson,f::F

What is:

(F) b ill-typed!(Parent) b ::Parent(Parent) d ::Parent(Child1) a ?

Parent

Child1

Child2

Grandson

F

2013 B. Wolff, L2-PO&GL, Introduction 46

Static and Dynamic Types

Casting in a class hierarchy:

Syntax: (<type>)<expr> We assume to have created

objects:

a::Parent,b::Child1,c::Child2, d::Grandson,f::F

What is:

(F) b ill-typed(A) b ::A(A) d ::A(B) a always exception

F

Parent

Child1

Child2

Grandson

2013 B. Wolff, L2-PO&GL, Introduction 47

Syntax and Semantics of OCL / UML

Type-Tests e.oclIsType(oclType) Create a::Parent,b::Child1,c::Child2,

d::Grandson,f::F

a instanceof Parent ≠ ?a instanceof Child1 ≠ ?b instanceof Parent ≠ ?

((Child1)a instanceof Parent ≠ ?((Parent)b instanceof Parent ≠?

F

Parent

Child1

Child2

Grandson

2013 B. Wolff, L2-PO&GL, Introduction 48

Syntax and Semantics of OCL / UML

Type-Tests e.oclIsType(oclType) Create a::Parent,b::Child1,c::Child2,

d::Grandson,f::F

a instanceof Parent ≠ truea instanceof Child2 ≠ falseb instanceof Parent ≠ true

((Parent)c instanceof Child1 ≠ false((Parent)b instanceof Child1 ≠ true

(Casts do not change the (dynamic, « actual ») type)

F

Parent

Child1

Child2

Grandson

2013 B. Wolff, L2-PO&GL, Introduction 49

Conclusion

What is Object-Orientation ? ✔

A Gentle Review of Java (Concepts and Syntax) ✔ Types Control-structures Methods Classes Programs

Complements (1)

Inheritance and Casting ✔

Bertrand Meyer: Conception et program– mation orientées object, Eyrolles, 2008.

http://www.editions-eyrolles. com/Livre/9782212122701/ conception-et-programmation- orientees-objet

Bibliography

Bibliography

UML 2.0, Martin Fowler, Campus Press, 2004 Developing Applications with Java and UML, Paul R. Reed Jr., Addison Wesley, 2002 UML 2 et les Design Patterns, G. Larman, Campus Press, 2005 UML 2 en action, P. Roques, F. Vallée, Eyrolles 2004

Paul R. Reed Jr., Addison Wesley, 2002 The Unified Modeling Language User Guide, Grady Booch, James Rumbaugh, Ivar Jacobson, Addison-Wesley, 2005 Précis de Génie Logiciel, M.-C. Gaudel, B. Marre, F. Schlienger et G. Bernot, Masson, 1996 The Science of Programming, D. Gries, Springer Verlag, 1981

http://www.omg.org/gettingstarted/what_is_uml.htm http://www.eecs.ucf.edu/~leavens/JML/http://www.junit.org/