Sunteți pe pagina 1din 382

Programmation Orient ee Objet

Bertrand Estellon
D epartement dInformatique de Luminy Aix-Marseille Universit e

29 mai 2012

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

1 / 379

Java

Cours 1

La programmation orient ee objet (POO)

Les objectifs : Faciliter le d eveloppement et l evolution des applications ; Permettre le travail en equipe ; Augmenter la qualit e des logiciels (moins de bugs). Solutions propos ees : D ecoupler (s eparer) les parties des projets ; Limiter (et localiser) les modications lors des evolutions ; R eutiliser facilement du code.

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

2 / 379

Java

Cours 1

Le langage Java (utilis e dans ce cours)


Le langage Java : est un langage de programmation orient e objet cr e e par James Gosling et Patrick Naughton (Sun) pr esent e ociellement le 23 mai 1995. Les objectifs de Java : simple, orient e objet et familier ; robuste et s ur ; ind ependant de la machine employ ee pour lex ecution ; tr` es performant ; interpr et e, multi-t aches et dynamique.

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

3 / 379

Java

Cours 1

Autres langages orient e objet


C++ : tr` es utilis e C# : langage de Microsoft (appartient ` a .NET) Objective C : langage utilis e par Apple PHP : langage tr` es utilis e sur le Web Python Ruby Eiel Ada Smalltalk ... La syntaxe change mais le concept objet est le m eme !
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 4 / 379

Java

Cours 1

Mon premier programme Java


Le programme HelloWorld.java : class HelloWorld { p u b l i c s t a t i c v o i d main ( S t r i n g a r g [ ] ) { System . o u t . p r i n t l n ( H e l l o w o r l d ! ) ; } } Compilation et ex ecution : $ javac HelloWorld.java $ ls HelloWorld.java HelloWorld.class $ java HelloWorld Hello world !
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 5 / 379

Java

Cours 1

Commentaires

class HelloWorld { p u b l i c s t a t i c v o i d main ( S t r i n g a r g [ ] ) { / Commentaire sur p l u s i e u r s l i g n e s . / // s u r une s e u l e l i g n e . System . o u t . p r i n t l n ( H e l l o w o r l d ! ) ; } }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

6 / 379

Java

Cours 1

Les types primitifs

byte short int long oat double char boolean

entier entier entier entier otant otant caract` ere boolean

8 bits 16 bits 32 bits 64 bits 32 bits 64 bits 16 bits 1 bit

-128 ` a 127 -32768 ` a 32767 231 ` a 231 1 263 ` a 263 1

caract` eres Unicode false ou true

0 0 0 0 0.0 0.0 \u0000 false

int a = 12; double b = 1 3 . 5 ;

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

7 / 379

Java

Cours 1

Syntaxe
Tr` es proche de celle du C : c l a s s PetitProgramme { p u b l i c s t a t i c v o i d main ( S t r i n g a r g [ ] ) { f o r ( i n t i = 0 ; i < 1 0 0 ; i ++) System . o u t . p r i n t l n ( i ) ; boolean b = t r u e ; int k = 1; while ( b ) { i f ( k%100==0) b = f a l s e ; k++; } } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 8 / 379

Java

Cours 1

Les structures du C
En C, la d eclaration dune structure permet de d enir ses champs : s t r uc t DeuxEntiers { int x ; int y ; } typedef s t r u c t DeuxEntiers DeuxEntiers ; Lallocation de di erentes zones m emoires utilisant cette structure : D e u x E n t i e r s p1 = m a l l o c ( s i z e o f p1 ) ; D e u x E n t i e r s p2 = m a l l o c ( s i z e o f p2 ) ; Acc` es aux donn ees des structures : p r i n t f ( %d %d , p1>x , p1>y ) ; Il ny a aucun comportement ou service associ e aux structures
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 9 / 379

Java

Cours 1

Les structures du C
70 20 50 30

1 20 2

10

20 20

90 20

20 40 50

Programme
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 10 / 379

Java

Cours 1

Programmation Orient ee Objet (POO)

70 20 50 30 1 20 2

10

20 20 90 20 20 40 50

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

11 / 379

Java

Cours 1

Programmation Orient ee Objet (POO)


Un objet : rend un ensemble de services (interface de lobjet) contient des donn ees ( etat de lobjet)
AecterValeurs

10 20

CalculerSomme

Une classe est un moule pour fabriquer des objets. Elle : d enit les m ethodes (cest-` a-dire les services) d ecrit la structure des donn ees Un objet cr e e` a partir dune classe A est une instance de la classe A.
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 12 / 379

Java

Cours 1

D enir une classe


class Additionneur { i n t v1 , v2 ; void a f f e c t e r V a l e u r s ( i n t valeur1 , i n t v a l e u r 2 ) { v1 = v a l e u r 1 ; v2 = v a l e u r 2 ; } in t calculerSomme () { r e t u r n v1+v2 ; } }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

13 / 379

Java

Cours 1

Cr eer une instance


Cr eation dune instance avec le mot-cl e new : new A d d i t i o n n e u r ( ) ; Cette expression renvoie une r ef erence vers linstance cr e ee par new. Elle peut etre aect ee ` a une variable de type r ef erence vers un Additionneur . D eclaration dune variable de type r ef erence vers un Additionneur : A d d i t i o n n e u r add ; Aectation de la r ef erence ` a la variable : add = new A d d i t i o n n e u r ( ) ;

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

14 / 379

Java

Cours 1

Utilisation des m ethodes et acc` es aux donn ees


On acc` ede aux donn ees et aux m ethodes avec lop erateur . (point) : class ProgrammePrincipal { p u b l i c s t a t i c v o i d main ( S t r i n g a r g [ ] ) { A d d i t i o n n e u r add = new A d d i t i o n n e u r ( ) ; add . a f f e c t e r V a l e u r s ( 1 0 , 3 0 ) ; i n t r = add . c a l c u l e r S o m m e ( ) ; System . o u t . p r i n t l n ( r ) ; // a f f i c h e 4 0 . System . o u t . p r i n t l n ( add . v1 ) ; // a f f i c h e 1 0 . System . o u t . p r i n t l n ( add . v2 ) ; // a f f i c h e 3 0 . } } En Java, le compilateur v erie que le membre (m ethode ou attribut) existe en utilisant le type de la r ef erence.

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

15 / 379

Java

Cours 1

R ef erence null
Les variables de type r ef erence contienne la valeur null par d efaut. La valeur null signie quelle ne pointe vers aucune instance. Aectation de la valeur null ` a une variable : A d d i t i o n n e u r add = n u l l ; Lutilisation dune m ethode (ou dune donn ee) ` a partir dune variable de type r ef erence ` a null provoque une erreur ` a lex ecution : A d d i t i o n n e u r add = n u l l ; add . a f f e c t e r V a l e u r s ( 1 0 , 3 0 ) ; Exception in thread "main" java.lang.NullPointerException at ProgrammePrincipal.main(ProgrammePrincipal.java:4)

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

16 / 379

Java

Cours 1

Comparaison de r ef erences
Il est possible de comparer deux r ef erences : class ProgrammePrincipal { p u b l i c s t a t i c v o i d main ( S t r i n g a r g [ ] ) { A d d i t i o n n e u r add = new A d d i t i o n n e u r ( ) ; A d d i t i o n n e u r add2 = add ; i f ( add==add2 ) System . o u t . p r i n t l n ( add==add2 ) ; e l s e System . o u t . p r i n t l n ( add != add2 ) ; A d d i t i o n n e u r add3 = new A d d i t i o n n e u r ( ) ; i f ( add==add3 ) System . o u t . p r i n t l n ( add==add3 ) ; e l s e System . o u t . p r i n t l n ( add != add3 ) ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 17 / 379

Java

Cours 1

Destruction des instances


En Java, la destruction des instances est assur ee par le Garbage collector. Lorsquune instance nest plus accessible ` a partir des variables, elle peut etre d etruite automatiquement par Java. class ProgrammePrincipal { p u b l i c s t a t i c v o i d main ( S t r i n g a r g [ ] ) { A d d i t i o n n e u r add = new A d d i t i o n n e u r ( ) ; add . a f f e c t e r V a l e u r s ( 1 0 , 3 0 ) ; i n t r = add . c a l c u l e r S o m m e ( ) ; System . o u t . p r i n t l n ( r ) ; add = n u l l ; // Linstance cr e ee par le new peut etre d etruite .... } } Objectif : une r ef erence contient null ou d esigne un objet
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 18 / 379

Java

Cours 1

Destruction des instances (Autre exemple)


class Lien { Lien l ; } cla ss ProgrammePrincipal { public static Lien creerCycle () { L i e n l i e n 1 = new L i e n ( ) ; L i e n l i e n 2 = new L i e n ( ) ; L i e n l i e n 3 = new L i e n ( ) ; lien1 . l = lien2 ; lien2 . l = lien3 ; lien3 . l = lien1 ; return l i e n 1 ; } p u b l i c s t a t i c v o i d main ( S t r i n g a r g [ ] ) { Lien l i e n = creerCycle ( ) ; l i e n = null ; ... // Toutes les instances qui composent le cycle ne sont plus accessibles. } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 19 / 379

Java

Cours 1

Constructeur (D eclaration)
class Additionneur { i n t v1 , v2 ; Additionneur ( int valeur1 , int valeur2 ) { v1 = v a l e u r 1 ; v2 = v a l e u r 2 ; } Additionneur ( int valeur ) { v1 = v a l e u r ; v2 = v a l e u r ; } in t calculerSomme () { r e t u r n v1+v2 ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 20 / 379

Java

Cours 1

Constructeur par d efaut


Si aucun constructeur nest d eni, la classe a un constructeur par d efaut
public class A { int a = 1; int b = 2; }

est equivalent ` a
public class A { int a ; int b ; p u b l i c A( ) { a = 1; a = 2; } }

Conseil : ne pas initialiser les champs en dehors du constructeur


Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 21 / 379

Java

Cours 1

Constructeur (Utilisation)

class ProgrammePrincipal { p u b l i c s t a t i c v o i d main ( S t r i n g a r g [ ] ) { A d d i t i o n n e u r add1 = new A d d i t i o n n e u r ( 1 0 , 2 0 ) ; A d d i t i o n n e u r add2 = new A d d i t i o n n e u r ( 2 0 ) ; i n t r 1 = add1 . c a l c u l e r S o m m e ( ) ; i n t r 2 = add2 . c a l c u l e r S o m m e ( ) ; System . o u t . p r i n t l n ( r 1 ) ; // a f f i c h e 30 System . o u t . p r i n t l n ( r 2 ) ; // a f f i c h e 40 } }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

22 / 379

Java

Cours 1

Mot-cl e this
class Additionneur { int valeur1 , valeur2 ; Additionneur ( int valeur1 , int valeur2 ) { this . valeur1 = valeur1 ; this . valeur2 = valeur2 ; } Additionneur ( int valeur ) { valeur1 = valeur ; valeur2 = valeur ; } in t calculerSomme () { r e t u r n v a l e u r 1+v a l e u r 2 ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 23 / 379

Java

Cours 1

Mot-cl e this
class Additionneur { int valeur1 , valeur2 ; Additionneur ( int valeur1 , int valeur2 ) { this . valeur1 = valeur1 ; this . valeur2 = valeur2 ; } Additionneur ( int valeur ) { this ( valeur , valeur ) ; } in t calculerSomme () { r e t u r n v a l e u r 1+v a l e u r 2 ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 24 / 379

Java

Cours 1

Donn ees et m ethodes statiques


Les m ethodes et des donn ees statiques sont directement associ ees ` a la classe (et non aux instances de la classe) :
class Additionneur { static int c ; i n t v1 , v2 ; Additionneur ( int valeur1 , int valeur2 ) { v1 = v a l e u r 1 ; v2 = v a l e u r 2 ; } public s t a t i c void setConstant ( i n t constant ) { c = constant ; } public i n t calculerSomme () { r e t u r n v1+v2+c ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 25 / 379

Java

Cours 1

Donn ees et m ethodes statiques


Comme ces donn ees et m ethodes sont directement associ ees ` a la classe, il nest pas n ecessaire dinstancier la classe pour les utiliser :
cla ss ProgrammePrincipal { p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g ) { Additionneur . setConstant (1); A d d i t i o n n e u r add1 = new A d d i t i o n n e u r ( 1 0 , 1 0 ) ; A d d i t i o n n e u r add2 = new A d d i t i o n n e u r ( 2 0 , 2 0 ) ; System . o u t . p r i n t l n ( add1 . c a l c u l e r S o m m e ( ) ) ; // System . o u t . p r i n t l n ( add2 . c a l c u l e r S o m m e ( ) ) ; // Additionneur . c = 2; System . o u t . p r i n t l n ( add1 . c a l c u l e r S o m m e ( ) ) ; // System . o u t . p r i n t l n ( add2 . c a l c u l e r S o m m e ( ) ) ; // } }

ache 21 ache 41 ache 22 ache 42

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

26 / 379

Java

Cours 1

Donn ees et m ethodes statiques


Une m ethode statique ne peut utiliser que : des donn ees statiques ` a la classe ; des m ethodes statiques ` a la classe.
an de garantir (par transitivit e) lutilisation exclusive de donn ees statiques.

Lutilisation de this na aucun sens dans une m ethode statique :


class Additionneur { static int c ; ... public s t a t i c void setConstant ( i n t c ) { Additionneur . c = c ; } }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

27 / 379

Java

Cours 1

Les tableaux
D eclaration dune variable de type r ef erence vers un tableau de : int [ ] tableauDEntiers ; A d d i t i o n n e u r [ ] tableauDAdds ; Cr eation dun tableau : t a b l e a u D E n t i e r s = new i n t [ 1 0 ] ; t a b l e a u D A d d s = new A d d i t i o n n e u r [ 1 0 ] ; Utilisation dun tableau :
f o r ( i n t i = 0 ; i < t a b l e a u D A d d s . l e n g t h ; i ++) t a b l e a u D A d d s [ i ] = new A d d i t i o n n e u r ( i ,10 i ) ; int r = 1; f o r ( i n t i = t a b l e a u D A d d s . l e n g t h 1; i >= 0 ; i ) r = r tableauDAdds [ i ] . calculerSomme ( ) ;

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

28 / 379

Java

Cours 1

Les tableaux ` a plusieurs indices


D eclaration : int [ ] [ ] matriceDEntiers ; A d d i t i o n n e u r [ ] [ ] mat ric eDAdds ; Cr eation : mat ric eDAdds = new A d d i t i o n n e u r [ 1 0 ] [ ] ; f o r ( i n t i = 0 ; i < mat ric eDAdds . l e n g t h ; i ++) mat ric eDAdds [ i ] = new A d d i t i o n n e u r [ 5 ] ; ou mat ric eDAdds = new A d d i t i o n n e u r [ 1 0 ] [ 5 ] ; Tableaux non rectangulaires : mat ric eDAdds = new A d d i t i o n n e u r [ 1 0 ] [ ] ; f o r ( i n t i = 0 ; i < mat ric eDAdds . l e n g t h ; i ++) mat ric eDAdds [ i ] = new A d d i t i o n n e u r [ i + 1 ] ;
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 29 / 379

Java

Cours 1

Les exceptions et les tableaux


i n t [ ] t a b = new i n t [ 1 2 ] ; f o r ( i n t i = 0 ; i < t a b . l e n g t h ; i ++) t a b [ i ] = i ; System . o u t . p r i n t l n ( t a b [ 1 2 ] ) ;
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 12 at ProgrammePrincipal.main(ProgrammePrincipal.java:5)

i n t [ ] tab = n u l l ; System . o u t . p r i n t l n ( t a b [ 1 2 ] ) ;
Exception in thread "main" java.lang.NullPointerException at ProgrammePrincipal.main(ProgrammePrincipal.java:4)

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

30 / 379

Java

Cours 1

Cha nes de caract` eres


Trois classes permettent de g erer les cha nes de caract` eres : la classe String : cha ne invariable ; la classe StringBuer : cha ne modiable (multi-thread). la classe StringBuilder : cha ne modiable (mono-thread). D eclaration et cr eation : S t r i n g h = H e l l o ; S t r i n g w = World ; Concat enation : S t r i n g hw = h + + w + ! ; int c = 13; S t r i n g hw12c = h + + w + + 12 + + c ; La conversion est eect ee en utilisant lune des m ethodes statiques valueOf de la classe String.
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 31 / 379

Java

Cours 1

Cha nes de caract` eres


Achage : System . o u t . p r i n t ( hw ) ; System . o u t . p r i n t l n ( hw12c ) ; Comparaison : S t r i n g a1 = a ; S t r i n g a2 = a ; S t r i n g a3 = new S t r i n g ( a ) ; System . o u t . p r i n t l n ( a1==a2 ) ; // ache true System . o u t . p r i n t l n ( a1==a3 ) ; // ache false System . o u t . p r i n t l n ( a1 . e q u a l s ( a3 ) ) ; // ache true // ache Hello World ! // ache Hello World 12 13 // avec retour ` a la ligne

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

32 / 379

Java

Cours 1

Exemple : formulaire avec boutons


cla ss ProgrammePrincipal { p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g ) { F o r m u l a i r e f = new F o r m u l a i r e ( 2 ) ; f . a j o u t e r B o u t o n ( new Bouton ( o u v r i r , 1 0 , 1 0 , 2 0 , 2 0 ) ) ; f . a j o u t e r B o u t o n ( new Bouton ( a n n u l e r , 3 0 , 1 0 , 4 0 , 2 0 ) ) ; Bouton b ; b = f . d e t e c t e r C l i c (15 , 15); i f ( b!= n u l l ) b . a f f i c h e r T e x t e ( ) ; // ache ouvrir b = f . d e t e c t e r C l i c (35 , 15); i f ( b!= n u l l ) b . a f f i c h e r T e x t e ( ) ; // ache annuler b = f . d e t e c t e r C l i c (50 , 15); i f ( b!= n u l l ) b . a f f i c h e r T e x t e ( ) ; // nache rien } }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

33 / 379

Java

Cours 1

Exemple : formulaire avec boutons


class Formulaire { i n t nbBoutons ; Bouton [ ] b o u t o n s ; F o r m u l a i r e ( i n t maxNbBoutons ) { b o u t o n s = new Bouton [ maxNbBoutons ] ; nbBoutons = 0 ; } v o i d a j o u t e r B o u t o n ( Bouton bo ut on ) { b o u t o n s [ nbBoutons ] = b ou t o n ; nbBoutons++; } Bouton d e t e c t e r C l i c ( i n t x , i n t y ) { f o r ( i n t i = 0 ; i < nbBoutons ; ++i ) i f ( boutons [ i ] . d e t e c t e r C l i c ( x , y )) return boutons [ i ] ; return null ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 34 / 379

Java

Cours 1

Exemple : formulaire avec boutons


c l a s s Bouton { String texte ; i n t x1 , y1 , x2 , y2 ; Bouton ( S t r i n g t e x t e , this . texte = texte t h i s . x1 = x1 ; t h i s t h i s . x2 = x2 ; t h i s } i n t x1 , i n t y1 , i n t x2 , i n t y2 ) { ; . y1 = y1 ; . y2 = y2 ;

b o olea n d e t e c t e r C l i c ( i n t x , i n t y ) { r e t u r n x>=x1 && x<=x2 && y>=y1 && y <= y2 ; } void a f f i c h e r T e x t e () { System . o u t . p r i n t l n ( t e x t e ) ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 35 / 379

Java

Cours 1

Packages
Un package est un ensemble de classes. Deux classes peuvent avoir le m eme nom si elles appartiennent ` a deux paquets di erents. Une ligne package nomPaquet ; (plac ee au d ebut du chier source) permet de placer les classes d ecrites dans le chier dans le paquet nomPaquet. Par d efaut, les classes sont plac ees dans le paquet sans nom. Un nom de paquet est une suite didenticateurs s epar es de points. Ex : monPaquet, mon.Paquet, java.awt Les noms de paquet qui commencent par java. sont r eserv es ` a Java.
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 36 / 379

Java

Cours 1

Noms des classes et mot-cl e import

Une classe peut etre d esign ee en pr exant le nom de la classe par celui du paquet (java.awt.List = classe List du paquet java.awt). Une classe C du paquet nomPaquet peut etre d esign ee par son nom :
depuis les classes du paquet nomPaquet depuis les chiers qui contiennent import nomPaquet.C depuis les chiers qui contiennent import nomPaquet.*

Les classes du paquet java.lang sont toujours import ees : ce paquet contient les classes fondamentales de Java (Object, String...).

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

37 / 379

Java

Cours 1

Packages et modicateur public


Par d efaut, une classe ou une m ethode est non-publique : elle nest accessible que depuis les classes du m eme paquet. Une classe ou un membre public est accessible de nimporte o` u. Pour rendre une classe ou un membre public : public class ClassePublique { public int proprietePublique ; public void methodePublique ( ) { } } Si un chier contient une classe publique, le nom du chier doit etre form e du nom de la classe suivi de .java. Un chier ne peut contenir quune seule classe publique.
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 38 / 379

Java

Cours 1

Modicateur private et encapsulation


Un membre priv e nest accessible que par les m ethodes de la classe qui le contient. Pour rendre un membre priv e, on utilise le modicateur private : public class ClassePublique { private int proprietePrivee ; private void methodePrivee ( ) { } } Encapsulation : Tout ce qui participe ` a limpl ementation des services doit etre priv e (an de permettre la modication de limpl ementation des services sans risquer dimpacter les autres classes)

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

39 / 379

Java

Cours 1

Point dentr ee dun programme


Le programme HelloWorld.java : public class HelloWorld { p u b l i c s t a t i c v o i d main ( S t r i n g a r g [ ] ) { System . o u t . p r i n t l n ( H e l l o w o r l d ! ) ; f o r ( i n t i = 0 ; i < a r g . l e n g t h ; i ++) System . o u t . p r i n t l n ( a r g [ i ] ) ; } } $ javac HelloWorld.java $ ls HelloWorld.java HelloWorld.class $ java HelloWorld toto aaa Hello world ! toto aaa
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 40 / 379

Java

Cours 1

Convention de nommage (respect ee par Java)


Premi` ere lettre en majuscule pour les noms des classes Premi` ere lettre en minuscule pour les noms des membres Ensuite, premi` ere lettre de chaque mot en majuscule Noms simples et descriptifs Nutiliser que des lettres et des chires
c l a s s MaP i l e { p r i v a t e i n t maP i l e [ ] = new i n t [ 1 0 0 ] ; private int t a i l l e = 0; public void e mpilerE n t i e r ( i n t e n t i e r ) { m a P i l e [ t a i l l e ] = e n t i e r ; t a i l l e ++; } public int depi ler Enti er () { t a i l l e ; r e t u r n m a P i l e [ t a i l l e ] ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 41 / 379

Java

Cours 1

R esum e du cours
Les points abord es pendant ce cours : Objets, classes et instances Variables de type r ef erence D enir une classe Instancier une classe D enir et utiliser des constructeurs Destruction des instances (Garbage collector) Mot-cl e this Membres statiques Les tableaux Les cha nes de caract` eres Organisation en packages Convention de nommage
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 42 / 379

Java

Cours 2

R esum e du cours pr ec edent


Les points abord es pendant ce cours : Objets, classes et instances Variables de type r ef erence D enir une classe Instancier une classe D enir et utiliser des constructeurs Destruction des instances (Garbage collector) Mot-cl e this Membres statiques Les tableaux Les cha nes de caract` eres Organisation en packages Convention de nommage
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 43 / 379

Java

Cours 2

Rappel : Programmation Orient ee Objet (POO)

70 20 50 30 1 20 2

10

20 20 90 20 20 40 50

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

44 / 379

Java

Cours 2

Rappel : Programmation Orient ee Objet (POO)


Un objet : rend un ensemble de services (interface de lobjet) contient des donn ees ( etat de lobjet)
AecterValeurs

10 20

CalculerSomme

Une classe est un moule pour fabriquer des objets. Elle : d enit les m ethodes (cest-` a-dire les services) d ecrit la structure des donn ees Un objet cr e e` a partir dune classe A est une instance de la classe A.
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 45 / 379

Java

Cours 2

Abstraction
Des objets impl ementant des services identiques de fa cons di erentes :
acher(String s)

Telephone

alerter()

sonner()

acher(String s)

alerter()

acher(String s) Ordinateur

alerter()

Les objets impl ementent les m ethodes acher(String s) et alerter()


Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 46 / 379

Java

Cours 2

Abstraction
Objectifs : Traiter des objets en utilisant les services quils partagent :
f o r ( i n t i = 0 ; i < a f f i c h e u r s . l e n g t h ; i ++) afficheurs [ i ]. afficher (s) ; }

Ecrire un programme en supposant que les objets manipul es impl ementent certains services :

boolean e s t O r d o n n e ( Comparable t a b [ ] ) { f o r ( i n t i = 0 ; i < t a b . l e n g t h 1 ; i ++) i f ( t a b [ i ] . compareTo ( t a b [ i +1]) > 0 ) r e t u r n f a l s e ; return true ; } Si le tableau contient des objets comparables alors cette m ethode d etermine si le tableau est ordonn e
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 47 / 379

Java

Cours 2

Description dune interface


Description dune Interface en Java : public i n t e r f a c e Afficheur { / A f f i c h e l a c h a i n e de c a r a c t e r e s s . @param s l a c h a i n e a a f f i c h e r . / public void a f f i c h e r ( S t r i n g s ) ; / Alerte l u t i l i s a t e u r . / public void a l e r t e r ( ) ; } Une interface peut etre vue comme un contrat entre celui qui utilise les objets et celui qui les impl emente.
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 48 / 379

Java

Cours 2

Impl ementation dune interface


c l a s s Telephone implements A f f i c h e u r { public void a f f i c h e r ( String s ) { System . o u t . p r i n t l n ( s ) ; } void a l e r t e r () { a f f i c h e r ( A l e r t e ! ! ! ) ; } void sonner ( ) { System . o u t . p r i n t l n ( b i p ! ! ) ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 49 / 379

Java

Cours 2

Impl ementation dune interface


cla ss Ordinateur implements A f f i c h e u r { S t r i n g nom ; p u b l i c O r d i n a t e u r ( S t r i n g nom ) { t h i s . nom = nom ; } public void a f f i c h e r ( String s ) { System . o u t . p r i n t l n ( nom+ : +s ) ; } void a l e r t e r () { System . o u t . p r i n t l n ( A l e r t e de +nom ) ; }
Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

50 / 379

Java

Cours 2

R ef erences et interfaces
D eclaration dune variable de type r ef erence vers une instance dune classe qui impl emente linterface Acheur : Afficheur aff ; Il nest pas possible dinstancier une interface : A f f i c h e u r a f f = new A f f i c h e u r ( ) ; // interdit ! a f f . a f f i c h e r ( t o t o ) ; // que faire ? Il est possible dinstancier une classe qui impl emente une interface : T e l e p h o n e t = new T e l e p h o n e ( ) ; et de mettre la r ef erence dans une variable de type Acheur : Afficheur aff1 = t ; A f f i c h e u r a f f 2 = new O r d i n a t e u r ( t r u c ) ; A f f i c h e u r a f f 3 = new I n t e g e r ( 2 ) // impossible ! ! Transtypage vers le haut (upcasting)
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 51 / 379

Java

Cours 2

R ef erences et interfaces
Utilisation dobjets qui impl ementent linterface :
class ProgrammePrincipal { void a f f i c h e r C h a i n e ( A f f i c h e u r [ ] a f f i c h e u r s , S t r i n g s ) { f o r ( u n s i g n e d i n t i = 0 ; i < a f f i c h e u r s . l e n g t h ; i ++) afficheurs [ i ]. afficher (s) ; } v o i d a f f i c h e r T a b l e a u ( S t r i n g [ ] tab , A f f i c h e u r a ) { f o r ( u n s i g n e d i n t i = 0 ; i < t a b . l e n g t h ; i ++) a . a f f i c h e r ( tab [ i ] ) ; } }

V erication ` a la compilation : A f f i c h e u r a f f = new T e l e p h o n e ( ) ; a f f . s o n n e r ( ) ; // impossible (ne fait pas partie de linterface)


Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 52 / 379

Java

Cours 2

Polymorphisme
Le choix de la m ethode ` a ex ecuter ne peut etre fait qu` a lex ecution :
A f f i c h e u r [ ] a f f i c h e u r s = new A f f i c h e u r [ 2 ] ; a f f i c h e u r s [ 0 ] = new T e l e p h o n e ( ) ; a f f i c h e u r s [ 1 ] = new O r d i n a t e u r ( pc ) ; Random r = new Random ( ) ; // instanciation dun g en erateur al eatoire. i n t i = r . n e x t I n t ( 2 ) ; // tirage dun nombre en 0 et 1. a f f i c h e u r s [ i ] . a f f i c h e r ( mon message ) ;

Si i=0, le programme ache mon message. Si i=1, le programme ache pc : mon message. (En C, l editeur de liens d etermine ` a la compilation les appels ` a eectuer)

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

53 / 379

Java

Cours 2

R esum e
Une interface est un ensemble de signatures de m ethodes. Une classe peut impl ementer une interface : elle doit pr eciser le comportement de chacune des m ethodes de linterface. Il est possible de d eclarer une variable pouvant contenir des r ef erences vers des instances de classes qui impl ementent linterface. Java v erie ` a la compilation que toutes les aectations et les appels de m ethodes sont corrects. Le choix du code qui va etre ex ecut e est d ecid e` a lex ecution (en fonction de linstance point ee par la r ef erence).

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

54 / 379

Java

Cours 2

Impl ementations multiples


interface Visualisable { / Ache une cha ne de caract` eres qui represente lobjet. / public void v i s u a l i s e r ( ) ; } interface Pile { / Empile la valeur v sur la pile. @param v la valeur ` a empiler . / public void empiler ( i n t v ) ; / D epile une valeur sur la pile. @ r e t u r n la valeur d epil ee . / public int depiler ( ) ; }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 55 / 379

Java

Cours 2

Impl ementations multiples


Impl ementation des deux interfaces pr ec edentes :
c l a s s P i l e V i s u a l i s a b l e implements V i s u a l i s a b l e , P i l e { i n t [ ] tab ; i n t s i z e ; public P i l e V i s u a l i s a b l e ( int capacite ) { t a b = new i n t [ c a p a c i t e ] ; s i z e = 0 ; } p u b l i c v o i d e m p i l e r ( i n t v ) { t a b [ s i z e ] = v ; s i z e ++; } p u b l i c i n t d e p i l e r ( ) { s i z e ; r e t u r n t a b [ s i z e ] ; } public void v i s u a l i s e r () { f o r ( i n t i = 0 ; i < s i z e ; i ++) System . o u t . p r i n t ( t a b [ i ]+ ) ; System . o u t . p r i n t l n ( ) ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 56 / 379

Java

Cours 2

Impl ementations multiples


Impl ementation dune des deux interfaces :
c l a s s S t r i n g V i s u a l i s a b l e implements V i s u a l i s a b l e { String s ; public Str ingVisualisable ( String s ) { this . s = s ; } public void v i s u a l i s a b l e () { System . o u t . p r i n t l n ( s ) ; } }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

57 / 379

Java

Cours 2

Impl ementations multiples


Exemple : V i s u a l i s a b l e [ ] t a b = new V i s u a l i s a b l e [ 3 ] ; t a b [ 0 ] = new S t r i n g V i s u a l i s a b l e ( b o n j o u r ) ; P i l e V i s u a l i s a b l e p = new P i l e V i s u a l i s a b l e ( 1 0 ) ; tab [ 1 ] = p ; t a b [ 2 ] = new S t r i n g V i s u a l i s a b l e ( s a l u t ) ; p . empiler (10); p . empiler (30); System . o u t . p r i n t l n ( p . d e p i l e r ( ) ) ; p . empiler (12); f o r ( i n t i = 0 ; i < t a b . l e n g t h ; i ++) tab [ i ] . v i s u a l i s e r ( ) ; Quache ce programme ` a l ecran ?
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 58 / 379

Java

Cours 2

Impl ementations multiples


V erication des types ` a la compilation : V i s u a l i s a b l e [ ] t a b = new V i s u a l i s a b l e [ 3 ] ; t a b [ 0 ] = new S t r i n g V i s u a l i s a b l e ( b o n j o u r ) ; P i l e p = new P i l e V i s u a l i s a b l e ( 1 0 ) ; t a b [ 1 ] = p ; Erreur ` a la compilation (Une pile nest pas visualisable) ! t a b [ 2 ] = new S t r i n g V i s u a l i s a b l e ( s a l u t ) ; p . empiler (10); p . empiler (30); System . o u t . p r i n t l n ( p . d e p i l e r ( ) ) ; p . empiler (12); f o r ( i n t i = 0 ; i < t a b . l e n g t h ; i ++) tab [ i ] . v i s u a l i s e r ( ) ;

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

59 / 379

Java

Cours 2

Exemple : Formes cliquables


G1 G2 R1 R2 R3

G3 R4 R5 R6

Les formes sont regroup ees de fa con hi erarchique. Seuls les formes grises captent les clics. Lorsque lutilisateur clique sur une forme grise, le programme doit acher les noms des formes travers es par le clic. Exemple : si on clique dans le rectangle R5, on traverse R5 G3 G1.
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 60 / 379

Java

Cours 2

Exemple : Formes cliquables


Toutes les formes vont impl ementer linterface suivante :
interface Cliquable { / Propage les cons equences dun clic @param x coordonn ee x du clic @param y coordonn ee y du clic @ r e t u r n true si le point touche un point gris de la forme, false sinon / p u b l i c boolean t r a i t e r C l i c ( i n t x , i n t y ) ; }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

61 / 379

Java

Cours 2

Exemple : Formes cliquables


c l a s s R e c t a n g l e implements C l i q u a b l e { i n t x1 , y1 , x2 , y2 , numero ; R e c t a n g l e ( i n t x1 , i n t y1 , i n t x2 , i n t y2 , i n t numero ) { t h i s . x1 = x1 ; t h i s . x2 = x2 ; t h i s . y1 = y1 ; t h i s . y2 = y2 ; t h i s . numero = numero ; } p u b l i c bo o le a n t r a i t e r C l i c ( i n t x , i n t y ) { i f ( x>=x1 && x<=x2 && y>=y1 && y<=y2 ) { System . o u t . p r i n t l n ( R +numero ) ; return true ; } return f a l s e ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 62 / 379

Java

Cours 2

Exemple : Formes cliquables


c l a s s Groupe implements C l i q u a b l e { i n t numero , s i z e ; Cliquable [ ] elements ; Groupe ( i n t c a p a c i t e , i n t numero ) { e l e m e n t s = new C l i q u a b l e [ c a p a c i t e ] ; t h i s . numero = numero ; }

size = 0;

v o i d a j o u t e r E l e m e n t ( C l i q u a b l e c ) { e l e m e n t s [ s i z e ]= c ; s i z e ++;} p u b l i c bo o le a n t r a i t e r C l i c ( i n t x , i n t y ) { b oolea n r e s = f a l s e ; f o r ( i n t i = 0 ; i < s i z e ; i ++) i f ( elements [ i ] . t r a i t e r C l i c (x , y )) r e s = true ; i f ( r e s ) System . o u t . p r i n t l n ( G +numero ) ; return res ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 63 / 379

Java

Cours 2

Exemple : Formes cliquables


Exemple dutilisation : Groupe g1 = new Groupe ( 4 , 1 ) ; Groupe g2 = new Groupe ( 2 , 2 ) ; Groupe g3 = new Groupe ( 2 , 3 ) ; g1 . a j o u t e r E l e m e n t ( g2 ) ; g1 . a j o u t e r E l e m e n t ( g3 ) ; g2 . a j o u t e r E l e m e n t ( new R e c t a n g l e ( 1 0 , 1 0 , 4 0 , 4 0 , 1 ) ) ; g2 . a j o u t e r E l e m e n t ( new R e c t a n g l e ( 5 0 , 2 0 , 7 0 , 3 0 , 2 ) ) ; g1 . a j o u t e r E l e m e n t ( new R e c t a n g l e ( 8 0 , 1 0 , 9 0 , 3 0 , 3 ) ) ; g1 . a j o u t e r E l e m e n t ( new R e c t a n g l e ( 2 0 , 6 0 , 5 0 , 8 0 , 4 ) ) ; g3 . a j o u t e r E l e m e n t ( new R e c t a n g l e ( 6 0 , 4 0 , 7 0 , 8 0 , 5 ) ) ; g3 . a j o u t e r E l e m e n t ( new R e c t a n g l e ( 8 0 , 5 0 , 1 0 0 , 7 0 , 6 ) ) ; g1 . t r a i t e r C l i c ( 6 5 , 6 0 ) ; Quache ce programme ?
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 64 / 379

Java

Cours 2

Exemple : Formes cliquables Ajout des disques

G1 G2 D1 R2 R3

G3 D3 R5 D2

Que faut-il modier pour g erer les disques ?

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

65 / 379

Java

Cours 2

Exemple : Formes cliquables Ajout des disques


p u b l i c c l a s s D i s q u e implements C l i q u a b l e { i n t x , y , r , numero ; p u b l i c D i s q u e ( i n t x , i n t y , i n t r , i n t numero ) { this . x = x ; this . y = y ; this . r = r ; t h i s . numero = numero ; } p u b l i c b o o le a n t r a i t e r C l i c ( i n t x , i n t y ) { i n t dx = x t h i s . x , dy = y t h i s . y ; i f ( Math . s q r t ( dx dx+dy dy)<= r ) { System . o u t . p r i n t l n ( D+numero ) ; return true ; } return f a l s e ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 66 / 379

Java

Cours 2

Exemple : Formes cliquables Ajout des disques


Exemple dutilisation : Groupe g1 = new Groupe ( 4 , 1 ) ; Groupe g2 = new Groupe ( 2 , 2 ) ; Groupe g3 = new Groupe ( 2 , 3 ) ; g1 . a j o u t e r E l e m e n t ( g2 ) ; g1 . a j o u t e r E l e m e n t ( g3 ) ; g2 . a j o u t e r E l e m e n t ( new D i s q u e ( 2 5 , 2 5 , 2 5 , 1 ) ) ; g2 . a j o u t e r E l e m e n t ( new R e c t a n g l e ( 5 0 , 2 0 , 7 0 , 3 0 , 2 ) ) ; g1 . a j o u t e r E l e m e n t ( new R e c t a n g l e ( 8 0 , 1 0 , 9 0 , 3 0 , 3 ) ) ; g1 . a j o u t e r E l e m e n t ( new D i s q u e ( 3 5 , 7 0 , 2 0 , 3 ) ) ; g3 . a j o u t e r E l e m e n t ( new R e c t a n g l e ( 6 0 , 4 0 , 7 0 , 8 0 , 5 ) ) ; g3 . a j o u t e r E l e m e n t ( new D i s q u e ( 9 0 , 6 0 , 2 0 , 2 ) ) ; g1 . t r a i t e r C l i c ( 9 2 , 6 5 ) ; Quache ce programme ?
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 67 / 379

Java

Cours 2

Exemple : Formes cliquables Observateurs


G1 G2 D1 R2 R3

G3 D3
onClick()

R5

D2

onClick() onClick() onClick()

Observeur1

Observeur2

Observeur3

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

68 / 379

Java

Cours 2

Exemple : Formes cliquables Observateurs

Interface pour les echanges entre les formes et les observateurs : public interface C l i c k L i s t e n e r { / Invoqu ee quand lobjet est cliqu e. / public void o n C l i c k ( C l i q u a b l e c ) ; }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

69 / 379

Java

Cours 2

Exemple : Formes cliquables Observateurs


c l a s s R e c t a n g l e implements C l i q u a b l e { .... C l i c k L i s t e n e r [ ] l i s t e n e r s = new C l i c k L i s t e n e r [ 1 0 0 ] ; int nbListeners = 0; ... void a d d C l i c k L i s t e n e r ( C l i c k L i s t e n e r l ) { l i s t e n e r s [ n b L i s t e n e r s ] = l ; n b L i s t e n e r s ++; } p u b l i c bo o le a n t r a i t e r C l i c ( i n t x , i n t y ) { i f ( x>=x1 && x<=x2 && y>=y1 && y<=y2 ) { f o r ( i n t i = 0 ; i < n b L i s t e n e r s ; i ++) l i s t e n e r s [ i ] . onClick ( this ); return true ; } return f a l s e ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 70 / 379

Java

Cours 2

Exemple : Formes cliquables Observateurs


c l a s s D i s q u e implements C l i q u a b l e { .... C l i c k L i s t e n e r [ ] l i s t e n e r s = new C l i c k L i s t e n e r [ 1 0 0 ] ; int nbListeners = 0; ... void a d d C l i c k L i s t e n e r ( C l i c k L i s t e n e r l ) { l i s t e n e r s [ n b L i s t e n e r s ] = l ; n b L i s t e n e r s ++; } p u b l i c bo o le a n t r a i t e r C l i c ( i n t x , i n t y ) { i n t dx = x t h i s . x , dy = y t h i s . y ; i f ( Math . s q r t ( dx dx + dy dy ) <= r ) { f o r ( i n t i = 0 ; i < n b L i s t e n e r s ; i ++) l i s t e n e r s [ i ] . onClick ( this ); return true ; } return f a l s e ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 71 / 379

Java

Cours 2

Exemple : Formes cliquables Observateurs


Premi` ere impl ementation de linterface ClickListener :
p u b l i c c l a s s S i m p l e C l i c k L i s t e n e r implements C l i c k L i s t e n e r { S t r i n g msg ; p u b l i c S i m p l e C l i c k L i s t e n e r ( S t r i n g msg ) { t h i s . msg = msg ; } public void onClick ( C l i q u a b l e c ) { System . o u t . p r i n t l n ( C l i c : + msg ) ; } }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

72 / 379

Java

Cours 2

Exemple : Formes cliquables Observateurs


Exemple dutilisation :
Groupe g1 = new Groupe ( 4 , 1 ) ; R e c t a n g l e r 1 = new R e c t a n g l e ( 1 0 , 1 0 , 3 0 , 3 0 , 1 ) ; D i s q u e d1 = new D i s q u e ( 2 0 , 2 0 , 5 , 1 ) ; g1 . a j o u t e r E l e m e n t ( r 1 ) ; g1 . a j o u t e r E l e m e n t ( d1 ) ; r 1 . a d d C l i c k L i s t e n e r ( new S i m p l e C l i c k L i s t e n e r ( R e c t a n g l e 1 ) ) ; d1 . a d d C l i c k L i s t e n e r ( new S i m p l e C l i c k L i s t e n e r ( D i s q u e 1 ) ) ; S i m p l e C l i c k L i s t e n e r s c l = new S i m p l e C l i c k L i s t e n e r ( c o o l ! ! ) ; r1 . a d d C l i c k L i s t e n e r ( s c l ) ; d1 . a d d C l i c k L i s t e n e r ( s c l ) ; g1 . t r a i t e r C l i c ( 2 0 , 2 0 ) ; g1 . t r a i t e r C l i c ( 1 0 , 1 0 ) ;

Quache ce programme ?
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 73 / 379

Java

Cours 2

Exemple : Formes cliquables Observateurs


Classe anonyme :
R e c t a n g l e r = new R e c t a n g l e ( 1 0 , 1 0 , 4 0 , 4 0 , 1 ) ; C l i c k L i s t e n e r c l = new C l i c k L i s t e n e r ( ) { public void onClick ( C l i q u a b l e c ) { System . o u t . p r i n t l n ( s u p e r ! ! ) ; } }; r . addClickListener ( cl ); r . t r a i t e r C l i c (20 , 20);

Sans variable interm ediaire (moins lisible) :


R e c t a n g l e r = new R e c t a n g l e ( 1 0 , 1 0 , 4 0 , 4 0 , 1 ) ; r . a d d C l i c k L i s t e n e r ( new C l i c k L i s t e n e r ( ) { public void onClick ( C l i q u a b l e c ) { System . o u t . p r i n t l n ( s u p e r ! ! ) ; } }); r . t r a i t e r C l i c (20 , 20);
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 74 / 379

Java

Cours 2

Exemple : Formes cliquables Observateurs


Transtypage vers le bas (downcasting) :
p u b l i c c l a s s R e c t a n g l e C l i c k L i s t e n e r implements C l i c k L i s t e n e r { public void onClick ( C l i q u a b l e c ) { Rectangle r = ( Rectangle ) c ; System . o u t . p r i n t l n ( R e c t a n g l e : + r . numero ) ; } }

Exemple :
R e c t a n g l e r = new R e c t a n g l e ( 1 0 , 1 0 , 4 0 , 4 0 , 6 ) ; r . a d d C l i c k L i s t e n e r ( new R e c t a n g l e C l i c k L i s t e n e r ( ) ) ; r . t r a i t e r C l i c (20 , 20);

Quache ce programme ?

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

75 / 379

Java

Cours 2

Exemple : Formes cliquables Observateurs


Transtypage vers le bas (downcasting) :
p u b l i c c l a s s R e c t a n g l e C l i c k L i s t e n e r implements C l i c k L i s t e n e r { public void onClick ( C l i q u a b l e c ) { Rectangle r = ( Rectangle ) c ; System . o u t . p r i n t l n ( R e c t a n g l e : + r . numero ) ; } } D i s q u e d = new D i s q u e ( 2 0 , 2 0 , 2 0 , 4 ) ; d . a d d C l i c k L i s t e n e r ( new R e c t a n g l e C l i c k L i s t e n e r ( ) ) ; d . t r a i t e r C l i c (20 , 20);

Durant lex ecution :


Exception in thread "main" java.lang.ClassCastException: Disque cannot be cast to Rectangle at RectangleClickListener.onClick(RectangleClickListener.java:5) at Disque.traiterClic(Disque.java:23) at Test.main(Test.java:26) Java Result: 1 Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 76 / 379

Java

Cours 2

R esum e
Description dune interface Impl ementation dune interface R ef erence vers une classe impl ementant une interface Impl ementation de plusieurs interfaces Polymorphisme dobjet Classe anonyme Transtypage (vers le haut et vers le bas)

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

77 / 379

Java

Cours 3

R esum e des cours pr ec edents


Premier cours : Objets, classes et instances Variables de type r ef erence D enir et instancier une classe Tableaux, cha nes de caract` eres Packages Deuxi` eme cours : Description et impl ementation dinterfaces Polymorphisme dobjet Transtypage (vers le haut et vers le bas)

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

78 / 379

Java

Cours 3

Rappel : Interfaces et formes cliquables


G1 G2 D1 R2 R3

G3 D3
onClick()

R5

D2

onClick() onClick() onClick()

Observeur1

Observeur2

Observeur3

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

79 / 379

Java

Cours 3

Rappel : Interfaces et formes cliquables

Interface pour les echanges entre les formes et les observateurs : public interface C l i c k L i s t e n e r { / Invoqu ee quand lobjet est cliqu e. / public void o n C l i c k ( C l i q u a b l e c ) ; }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

80 / 379

Java

Cours 3

Rappel : Interfaces et formes cliquables


c l a s s R e c t a n g l e implements C l i q u a b l e { .... C l i c k L i s t e n e r [ ] l i s t e n e r s = new C l i c k L i s t e n e r [ 1 0 0 ] ; int nbListeners = 0; ... void a d d C l i c k L i s t e n e r ( C l i c k L i s t e n e r l ) { l i s t e n e r s [ n b L i s t e n e r s ] = l ; n b L i s t e n e r s ++; } p u b l i c bo o le a n t r a i t e r C l i c ( i n t x , i n t y ) { i f ( x>=x1 && x<=x2 && y>=y1 && y<=y2 ) { f o r ( i n t i = 0 ; i < n b L i s t e n e r s ; i ++) l i s t e n e r s [ i ] . onClick ( this ); return true ; } return f a l s e ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 81 / 379

Java

Cours 3

Rappel : Interfaces et formes cliquables


c l a s s D i s q u e implements C l i q u a b l e { .... C l i c k L i s t e n e r [ ] l i s t e n e r s = new C l i c k L i s t e n e r [ 1 0 0 ] ; int nbListeners = 0; ... void a d d C l i c k L i s t e n e r ( C l i c k L i s t e n e r l ) { l i s t e n e r s [ n b L i s t e n e r s ] = l ; n b L i s t e n e r s ++; } p u b l i c bo o le a n t r a i t e r C l i c ( i n t x , i n t y ) { i n t dx = x t h i s . x , dy = y t h i s . y ; i f ( Math . s q r t ( dx dx + dy dy ) <= r ) { f o r ( i n t i = 0 ; i < n b L i s t e n e r s ; i ++) l i s t e n e r s [ i ] . onClick ( this ); return true ; } return f a l s e ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 82 / 379

Java

Cours 3

Abstraction et extension
Le service associ e aux listeners est identique. On aimerait : d enir une classe FormeCliquable qui impl emente ce service ; sans perdre les sp ecicit es dun disque ou dun rectangle.
Interface Cliquable

traiterClic()

Observateur

onClick() Interface ClickListener

addClickListener()

traiterClic()

traiterClic()

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

83 / 379

Java

Cours 3

Extension
Lextension permet de cr eer une classe qui : conserve les services (propri et es et m ethodes) dune autre classe ; ajouter ses propres services (propri et es et m ethodes). En Java : On utilise le mot-cl e extends pour etendre une classe ; Une classe ne peut etendre quune seule classe.

Ne pas etendre quand une impl ementation dinterface sut !

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

84 / 379

Java

Cours 3

La classe FormeCliquable
p u b l i c c l a s s F o r m e C l i q u a b l e implements C l i q u a b l e { private ClickListener [ ] l i s t e n e r s ; private int nbListeners ; public FormeCliquable () { l i s t e n e r s = new C l i c k L i s t e n e r [ 1 0 0 ] ; nbListeners = 0; } public void a d d C l i c k L i s t e n e r ( C l i c k L i s t e n e r l ) { l i s t e n e r s [ n b L i s t e n e r s ] = l ; n b L i s t e n e r s ++; } p u b l i c b o o le a n t r a i t e r C l i c ( i n t x , i n t y ) { f o r ( i n t i = 0 ; i < n b L i s t e n e r s ; i ++) l i s t e n e r s [ i ] . onClick ( this ); return true ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 85 / 379

Java

Cours 3

Utilisation de lextension La classe Rectangle


public class Rectangle extends FormeCliquable { p u b l i c i n t x1 , y1 , x2 , y2 , numero ; R e c t a n g l e ( i n t x1 , t h i s . x1 = x1 ; t h i s . y1 = y1 ; t h i s . numero = } i n t y1 , i n t x2 , i n t y2 , i n t numero ) { t h i s . x2 = x2 ; t h i s . y2 = y2 ; numero ;

p u b l i c b o o le a n t r a i t e r C l i c ( i n t x , i n t y ) { i f ( x >= x1 && x <= x2 && y >= y1 && y <= y2 ) { super . t r a i t e r C l i c (x , y ) ; return true ; } return f a l s e ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 86 / 379

Java

Cours 3

Utilisation de lextension La classe Disque


p u b l i c c l a s s Disque extends FormeCliquable { p u b l i c i n t x , y , r , numero ; p u b l i c D i s q u e ( i n t x , i n t y , i n t r , i n t numero ) { this . x = x ; this . y = y ; this . r = r ; t h i s . numero = numero ; } p u b l i c b o o le a n t r a i t e r C l i c ( i n t x , i n t y ) { i n t dx = x t h i s . x , dy = y t h i s . y ; i f ( Math . s q r t ( dx dx + dy dy ) <= r ) { return super . t r a i t e r C l i c (x , y ) ; } return f a l s e ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 87 / 379

Java

Cours 3

Transtypage vers le haut (upcasting)


Lupcasting est toujours possible : Si la classe B etend la classe A, laectation dune r ef erence de type B dans une variable de type A est toujours possible.
(car tout ce quune instance de A sait faire, une instance de B sait le faire)

Exemple :
public class A { p u b l i c v o i d method1 ( ) { System . o u t . p r i n t l n ( m1 ) ; } } p u b l i c c l a s s B extends A { p u b l i c v o i d method2 ( ) { System . o u t . p r i n t l n ( m2 ) ; } } B b = new B ( ) ; A a = b ; // upcasting a . method1 ( ) ; // la m ethode est impl ement e a . method2 ( ) ; // erreur ` a la compilation : la classe A ne d enit pas cette m ethode
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 88 / 379

Java

Cours 3

Transtypage vers le bas (downcasting)


Lupcasting nest pas toujours possible : Si la classe B etend la classe A, laectation dune r ef erence de type A dans une variable de type B nest pas toujours possible. Exemple :
public class A { p u b l i c v o i d method1 ( ) { System . o u t . p r i n t l n ( m1 ) ; } } p u b l i c c l a s s B extends A { p u b l i c v o i d method2 ( ) { System . o u t . p r i n t l n ( m2 ) ; } } A B A B B a1 b1 a2 b2 b3 = = = = = new A ( ) ; new B ( ) ; b1 ; // upcasting ! (B) a2 ; // downcasting possible ! (B) a1 ; // downcasting impossible (erreur ` a lex ecution)
Programmation Orient ee Objet 29 mai 2012 89 / 379

Bertrand Estellon (DIL Aix-Marseille)

Java

Cours 3

Red enition de m ethodes et polymorphisme


Dans la classe Rectangle, nous avons red eni la m ethode traiterClic : La m ethode existe dans la classe FormeCliquable ; Une nouvelle impl ementation est donn ee dans la classe Rectangle.
public class A { p u b l i c v o i d a f f i c h e r N o m ( ) { System . o u t . p r i n t l n ( A ) ; } } p u b l i c c l a s s B extends A { p u b l i c v o i d a f f i c h e r N o m ( ) { System . o u t . p r i n t l n ( B ) ; } } B b = new B ( ) ; b . a f f i c h e r N o m ( ) ; // ache B A a = new A ( ) ; a . a f f i c h e r N o m ( ) ; // ache A a = b ; a . a f f i c h e r N o m ( ) ; // ache B

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

90 / 379

Java

Cours 3

Mot-cl e super
Le mot-cl e super permet dutiliser une m ethode d enie au dessus :
public class A { p u b l i c S t r i n g getName ( ) { r e t u r n A ; } }

p u b l i c c l a s s B1 e x t e n d s A { p u b l i c S t r i n g t e s t ( ) { r e t u r n getName ( ) ; }

/A/ }

p u b l i c c l a s s B2 e x t e n d s A { p u b l i c S t r i n g getName ( ) { r e t u r n B ; } p u b l i c S t r i n g t e s t ( ) { r e t u r n getName ( ) ; / B / } } p u b l i c c l a s s B3 e x t e n d s A { p u b l i c S t r i n g getName ( ) { r e t u r n B ; } p u b l i c S t r i n g t e s t ( ) { r e t u r n s u p e r . getName ( ) ; / A / } }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

91 / 379

Java

Cours 3

Mot-cl e super
Le mot-cl e super permet dutiliser une propri et e d enie au dessus :
public class A { p u b l i c S t r i n g name = A ; }

p u b l i c c l a s s B1 e x t e n d s A { p u b l i c S t r i n g t e s t ( ) { r e t u r n name ; }

/A/ }

p u b l i c c l a s s B2 e x t e n d s A { p u b l i c S t r i n g name = B ; p u b l i c S t r i n g t e s t ( ) { r e t u r n name ; / B / } } p u b l i c c l a s s B3 e x t e n d s A { p u b l i c S t r i n g name = B ; p u b l i c S t r i n g t e s t ( ) { r e t u r n s u p e r . name ; / A / } }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

92 / 379

Java

Cours 3

Rappel : Constructeur par d efaut


Si aucun constructeur nest d eni, la classe a un constructeur par d efaut
public class A { int a = 1; int b = 2; }

est equivalent ` a
public class A { int a ; int b ; p u b l i c A( ) { a = 1; a = 2; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 93 / 379

Java

Cours 3

Construction des instances et extension


Si une classe B etend une classe A, la construction dune instance de A est n ecessaire lors de la construction dune instance de B Un appel au constructeur de A est eectu e au d ebut du constructeur de B :
public class Rectangle extends FormeCliquable { p u b l i c i n t x1 , y1 , x2 , y2 , numero ; R e c t a n g l e ( i n t x1 , i n t y1 , i n t x2 , i n t y2 , i n t numero ) { / Appel du constructeur sans param` etre de la classe FormeCliquable / t h i s . x1 = x1 ; t h i s . x2 = x2 ; t h i s . y1 = y1 ; t h i s . y2 = y2 ; t h i s . numero = numero ; } ... }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 94 / 379

Java

Cours 3

Mot-cl e super lors de la construction


Sil ny a pas de constructeur vide dans la classe A, il faut pr eciser les param` etres du constructeur de A en utilisant le mot-cl e super :
p u b l i c c l a s s ClasseAvecNom { S t r i n g nom ; p u b l i c ClasseAvecNom ( S t r i n g nom ) { t h i s . nom = nom ; } } p u b l i c c l a s s M a Cl a sse e x t e n d s ClasseAvecNom { p u b l i c M a Cl a sse ( ) { s u p e r ( MaClasse ) ; ... } }

Remarque : la classe ClasseAvecNom na pas de constructeur vide car un constructeur avec un param` etre est d eni.
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 95 / 379

Java

Cours 3

Modicateur nal
Le modicateur nal permet de bloquer lextension dune classe ou la red enition dune m ethode. Exemple 1 :
f i n a l public class A { }

p u b l i c c l a s s B e x t e n d s A { } / Impossible car la classe A est nale /

Exemple 2 :
public class A { f i n a l p u b l i c v o i d method ( ) { } }

p u b l i c c l a s s B extends A { p u b l i c v o i d method ( ) { } / Impossible car la methode est nale dans A / }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

96 / 379

Java

Cours 3

Classes abstraites
Une classe dont limpl ementation est incompl` ete est dite abstraite. Les m ethodes non-impl ement ees sont dites abstaites. Une classe abstraite nest pas instanciable. Exemple :
p u b l i c a b s t r a c t c l a s s SansNom { v o i d a f f i c h e r N o m ( ) { System . o u t . p r i n t l n ( obt eni r Nom ( ) ) ; } a b s t r a c t S t r i n g o b t e ni r Nom ( ) ; } p u b l i c c l a s s A e x t e n d s SansNom { S t r i n g o b t e n i r N o m ( ) { r e t u r n A ; } } A a = new A ( ) ; a . a f f i c h e r N o m ( ) ; // ache A
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 97 / 379

Java

Cours 3

Utilisation des classes abstraites


public a b s t r a c t c l a s s FormeCliquable implements C l i q u a b l e { ClickListener [] listeners ; int nbListeners ; public FormeCliquable () { l i s t e n e r s = new C l i c k L i s t e n e r [ 1 0 0 ] ; nbListeners = 0; } void a d d C l i c k L i s t e n e r ( C l i c k L i s t e n e r l ) { l i s t e n e r s [ n b L i s t e n e r s ] = l ; n b L i s t e n e r s ++; } public void p r o c e s s L i s t e n e r () { f o r ( i n t i = 0 ; i < n b L i s t e n e r s ; i ++) l i s t e n e r s [ i ] . onClick ( this ); } public abstract boolean t r a i t e r C l i c ( i n t x , i n t y ) ; }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 98 / 379

Java

Cours 3

Utilisation des classes abstraites


p u b l i c c l a s s Disque extends FormeCliquable { i n t x , y , r , numero ; p u b l i c D i s q u e ( i n t x , i n t y , i n t r , i n t numero ) { this . x = x ; this . y = y ; this . r = r ; t h i s . numero = numero ; } p u b l i c b o o le a n t r a i t e r C l i c ( i n t x , i n t y ) { i n t dx = x t h i s . x , dy = y t h i s . y ; i f ( Math . s q r t ( dx dx + dy dy ) <= r ) { processListener (); return true ; } return f a l s e ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 99 / 379

Java

Cours 3

Rappel : Packages et modicateur public


Par d efaut, une classe ou une m ethode est non-publique : elle nest accessible que depuis les classes du m eme paquet. Une classe ou un membre publics est accessible de nimporte o` u. Pour rendre une classe ou un membre public : public class ClassePublique { public int proprietePublique ; public void methodePublique ( ) { } } Si chier contient une classe publique, le nom du chier doit etre form e du nom de la classe suivi de .java. Un chier ne peut contenir quune seule classe publique.
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 100 / 379

Java

Cours 3

Rappel : Modicateur private et encapsulation


Un membre priv e nest accessible que par les m ethodes de la classe qui le contient. Pour rendre un membre priv e, on utilise le modicateur private : public class ClassePublique { private int proprietePrivee ; private void methodePrivee ( ) { } } Encapsulation : Tout ce qui participe ` a limpl ementation des services doit etre priv e (an de permettre la modication de limpl ementation des services sans risquer dimpacter les autres classes)

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

101 / 379

Java

Cours 3

Modicateur protected
Un membre prot eg e est accessible depuis :
les m ethodes de la classe qui le contient ; des m ethodes des classes qui etendent la classe qui le contient.

Pour rendre un membre prot eg e, on utilise le modicateur protected : public class ClassePublique { protected i n t p r o p r i e t e P r o t e g e e ; protected void methodeProtegee ( ) { } } Utilisation possible : Commencer limpl ementation dun service dans une classe et la terminer dans les classes qui l etendent . Possible repr esentation : Les membres prot eg es forment une interface entre une classe et les classes qui l etendent.
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 102 / 379

Java

Cours 3

Utilisation du modicateur protected


p u b l i c a b s t r a c t c l a s s F o r m e C l i q u a b l e implements C l i q u a b l e { ClickListener [] listeners ; int nbListeners ; public FormeCliquable () { l i s t e n e r s = new C l i c k L i s t e n e r [ 1 0 0 ] ; nbListeners = 0; } void a d d C l i c k L i s t e n e r ( C l i c k L i s t e n e r l ) { l i s t e n e r s [ n b L i s t e n e r s ] = l ; n b L i s t e n e r s ++; } protected void p r o c e s s L i s t e n e r () { f o r ( i n t i = 0 ; i < n b L i s t e n e r s ; i ++) l i s t e n e r s [ i ] . onClick ( this ); } p u b l i c a b s t r a c t b oolean t r a i t e r C l i c ( i n t x , i n t y ) ; }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 103 / 379

Java

Cours 3

La classe Object

Par d efaut, les classes etendent la classe Object Consequence : le upcasting vers Object est toujours possible
MaCla sse Object o Object [ ] for ( int c = new MaClasse ( ) ; = c; t = new O b j e c t [ 1 0 ] ; i = 0 ; i < t ; i ++) { i f ( i %2==0) t [ i ] = new U n e C l a s s e ( ) ; e l s e t [ i ] = new U n e D e u x i e m e C l a s s e ( ) ;

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

104 / 379

Java

Cours 3

Rappel : Cha nes de caract` eres


Deux classes permettent de g erer les cha nes de caract` eres : la classe String : cha ne invariable ; la classe StringBuer : cha ne destin ee ` a etre modi ee (voir API). D eclaration et cr eation : S t r i n g h = H e l l o ; S t r i n g w = World ; Concat enation : S t r i n g hw = h + + w + ! ; int c = 13; S t r i n g hw12c = h + + w + + 12 + + c ; La conversion est eect ee en utilisant lune des m ethodes statiques valueOf de la classe String.
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 105 / 379

Java

Cours 3

La m ethode toString()
Une impl ementation possible des String.valueOf(...)
class String { ... public s t a t i c S t r i n g valueOf ( Object obj ) { i f ( o b j== n u l l ) r e t u r n n u l l ; else return obj . toString () ; } p u b l i c s t a t i c S t r i n g v a l u e O f ( boolean b ) { i f ( b ) return t r u e ; e l s e return f a l s e ; } ... }

Une impl ementation possible des System.out.print(...) :


public void p r i n t ( S t r i n g s ) { ecrire s sur la sortie ; } p u b l i c v o i d p r i n t ( b o olean b ) { p r i n t ( S t r i n g . v a l u e O f ( b ) ) ; } public void p r i n t ( Object obj ) { p r i n t ( S t r i n g . valueOf ( obj ) ) ; }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 106 / 379

Java

Cours 3

Red enir la m ethode toString()


Red enition de la m ethode toString() :
p u b l i c c l a s s M a Cl a sse { p r i v a t e i n t numero ; p u b l i c M a Cl a sse ( i n t numero ) { t h i s . numero = numero ; } public String toString () { } r e t u r n MaClasse +numero ; }

Exemple dutilisation :
M a Classe c1 = new M a Classe ( 1 ) ; M a Classe c2 = new M a Classe ( 2 ) ; System . o u t . p r i n t l n ( c1 . t o S t r i n g ( ) + + c2 . t o S t r i n g ( ) ) ; System . o u t . p r i n t l n ( c1 + + c2 ) ;

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

107 / 379

Java

Cours 3

Extension dinterfaces
Il est egalement possible d etendre une interface :

interface I t e r a t o r { boolean h a s N e x t ( ) ; Object next ( ) ; }

i n t e r f a c e L i s t I t e r a t o r extends I t e r a t o r { boolean h a s P r e v i o u s ( ) ; Object p r e v i o u s ( ) ; }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

108 / 379

Java

Cours 3

Extension dinterfaces
c l a s s V e c t o r I t e r a t o r implements L i s t I t e r a t o r { f i n a l private Vector v ; private int p ; public V e c t o r I t e r a t o r ( Vector v ) { this . v = v ; p = 0; } p u b l i c b o o le a n h a s P r e v i o u s ( ) { r e t u r n ( p > 0 ) ; } p u b l i c O b j e c t p r e v i o u s ( ) { p ; r e t u r n v . g e t ( p ) ; } p u b l i c b o o le a n h a s N e x t ( ) { r e t u r n p < v . s i z e ( ) ; } public Object next () { Object o = v . get (p ) ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 109 / 379

p++; r e t u r n o ;

Java

Cours 3

Extension dinterfaces
Exemples dutilisation : V e c t o r v = new V e c t o r ( ) ; ... L i s t I t e r a t o r i t e r a t o r = new V e c t o r I t e r a t o r ( v ) ; while ( i t e r a t o r . hasNext ( ) ) System . o u t . p r i n t l n ( i t e r a t o r . n e x t ( ) ) ; while ( i t e r a t o r . hasPrevious ( ) ) System . o u t . p r i n t l n ( i t e r a t o r . p r e v i o u s ( ) ) ; ... I t e r a t o r i t e r a t o r = new V e c t o r I t e r a t o r ( v ) ; while ( i t e r a t o r . hasNext ( ) ) System . o u t . p r i n t l n ( i t e r a t o r . n e x t ( ) ) ;

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

110 / 379

Java

Cours 3

R esum e
Abstraction Etendre une classe Transtypage (vers le haut et vers le bas) Red enition de m ethodes et polymorphisme mot-cl e super Construction des instances Modicateurs nal et protected Classes et m ethodes abstraites La classe Object La m ethode toString()
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 111 / 379

Java

Cours 4

R esum e des cours pr ec edents


Premier cours : Objets, classes, instances, r ef erences D enir et instancier une classe Deuxi` eme cours : Description et impl ementation dinterfaces Transtypage (vers le haut et vers le bas) Troisi` eme cours : Extension de classe Red enition de m ethodes et polymorphisme Classes et m ethodes abstraites La classe Object
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 112 / 379

Java

Cours 4

Classes internes
Il est possible de d enir une classe ` a lint erieur dune autre classe. Une telle classe est dite interne.
public class ListeChainee { private Maillon tete ; public ListeChainee () { tete = null ; } p u b l i c v o i d add ( i n t v ) { t e t e = new M a i l l o n ( v , t e t e ) ; } private s t a t i c class Maillon { final int valeur ; f i n a l Maillon suivant ; public Maillon ( int valeur , Maillon suivant ) { this . valeur = valeur ; this . suivant = suivant ; } } }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

113 / 379

Java

Cours 4

Classes internes
public c l a s s Vector { p r i v a t e Object [ ] array ; private int size ; ... p u b l i c I t e r a t o r i t e r a t o r ( ) { r e t u r n new V e c t o r I t e r a t o r ( t h i s ) ; } } p u b l i c c l a s s V e c t o r I t e r a t o r implements I t e r a t o r { private int position = 0; p r i v a t e Vector v ; public V e c t o r I t e r a t o r ( Vector v ) { t h i s . v = v ; } p u b l i c boolean hasNext ( ) { r e t u r n p o s i t i o n < v . s i z e ; } p u b l ic Object next () { Object o = v . array [ p o s i t i o n ] ; return o ; } p u b l i c v o i d remove ( ) { } } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 114 / 379

p o s i t i o n ++;

Java

Cours 4

Classes internes
Une classe interne peut utiliser les membres de la classe qui la contient :
public c l a s s Vector { p r i v a t e Object [ ] array ; private int size ; ... p u b l i c I t e r a t o r i t e r a t o r ( ) { r e t u r n new V e c t o r I t e r a t o r ( ) ; } p r i v a t e c l a s s V e c t o r I t e r a t o r implements I t e r a t o r { int position = 0; p u b l i c boolean hasNext ( ) { r e t u r n p o s i t i o n < s i z e ; } p u b l ic Object next () { Object o = array [ p o s i t i o n ] ; return o ; } p u b l i c v o i d remove ( ) { } } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 115 / 379

p o s i t i o n ++;

Java

Cours 4

Classes anonymes
public c l a s s Vector { ... public I t e r a t o r i t e r a t o r () { r e t u r n new I t e r a t o r ( ) { int position = 0; p u b l i c boolean hasNext ( ) { r e t u r n p o s i t i o n < s i z e ; } p u b l i c Object next () { Object o = array [ p o s i t i o n ] ; return o ; } p u b l i c v o i d remove ( ) { } }; } }

p o s i t i o n ++;

Syntaxe : new ClasseOuInterface() { impl ementation }


Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 116 / 379

Java

Cours 4

Introduction ` a AWT
Abstract Window Toolkit (AWT) = biblioth` eque graphique Java ; AWT a et e introduite d` es les premi` eres versions de Java ; AWT sert de fondement ` a Swing Swing = biblioth` eque de gestion de fen etre de JAVA.

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

117 / 379

Java

Cours 4

Composants
Une interface graphique est construite ` a partir de composants ; Un Composant est un el ement visible ; Un Composant etend la classe abstraite Component. Les composants de AWT : Button Canvas Checkbox Choice Label List Scrollbar Container TextComponent
TextArea TextField

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

118 / 379

Java

Cours 4

Conteneurs
Un conteneur est un composant ; Un conteneur peut contenir plusieurs composants ; Un conteneur etend la classe Container. Les principaux conteneurs de AWT : Panel
Applet

Window
Dialog
FileDialog JDialog (Swing)

Frame
JFrame (Swing)

JWindow (Swing)

JComponent (Swing)
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 119 / 379

Java

Cours 4

Exemple
Frame f r a m e = new Frame ( Ma f r a m e ) ; f r a m e . s e t P r e f e r r e d S i z e ( new D i m e n s i o n ( 2 0 0 , 2 0 0 ) ) ; P a n e l p a n e l = new P a n e l ( ) ; p a n e l . add ( new But ton ( Un b ou t o n ) ) ; p a n e l . add ( new Checkbox ( Truc , f a l s e ) ) ; C h o i c e c h o i c e = new C h o i c e ( ) ; c h o i c e . add ( c h o i x 1 ) ; c h o i c e . add ( c h o i x 2 ) ; p a n e l . add ( c h o i c e ) ; p a n e l . add ( new L a b e l ( l a b e l ) ) ; L i s t l i s t = new L i s t ( ) ; l i s t . add ( c h o i x 1 ) ; l i s t . add ( c h o i x 2 ) ; p a n e l . add ( l i s t ) ; p a n e l . add ( new T e x t F i e l d ( Truc ) ) ; T e x t A r e a t e x t A r e a = new T e x t A r e a ( Truc \ nTruc ) ; t e x t A r e a . setColumns ( 1 0 ) ; t e x t A r e a . setRows ( 3 ) ; p a n e l . add ( t e x t A r e a ) ; f r a m e . add ( p a n e l ) ; f r a m e . pack ( ) ; frame . s e t V i s i b l e ( true ) ;
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 120 / 379

Java

Cours 4

Exemple

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

121 / 379

Java

Cours 4

Gestionnaires de pr esentation
Un gestionnaire de pr esentation impl emente LayoutManager ; Chaque conteneur a un gestionnaire de pr esentation ; G` ere la position et la taille des composants pr esents dans le conteneur. Les principaux gestionnaires de pr esentation de AWT : BorderLayout BoxLayout CardLayout FlowLayout GridBagLayout GridLayout ...
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 122 / 379

Java

Cours 4

Gestionnaires de pr esentation
Chaque conteneur a un gestionnaire de pr esentation par d efaut :
Panel FlowLayout Window BorderLayout

Il est possible de changer le gestionnaire de pr esentation dun conteneur en utilisant la m ethode setLayout de la classe Container.
Frame f r a m e = new Frame ( Ma f r a m e ) ; P a n e l p a n e l = new P a n e l ( ) ; p a n e l . s e t L a y o u t ( new G r i d L a y o u t ( 2 , 2 ) ) ; p a n e l . add ( new But ton ( b1 ) ) ; p a n e l . add ( new But ton ( b2 ) ) ; p a n e l . add ( new But ton ( b3 ) ) ; p a n e l . add ( new But ton ( b4 ) ) ; f r a m e . add ( p a n e l ) ; f r a m e . pack ( ) ; frame . s e t V i s i b l e ( true ) ;
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 123 / 379

Java

Cours 4

Gestionnaires de pr esentation (BorderLayout)


Frame f r a m e = new Frame ( Ma f r a m e ) ; P a n e l p a n e l = new P a n e l ( ) ; p a n e l . s e t L a y o u t ( new B o r d e r L a y o u t ( ) ) ; p a n e l . add ( new But ton ( N) , B o r d e r L a y o u t .NORTH) ; p a n e l . add ( new But ton ( S ) , B o r d e r L a y o u t . SOUTH ) ; p a n e l . add ( new But ton ( C ) , B o r d e r L a y o u t . CENTER ) ; p a n e l . add ( new But ton ( W) , B o r d e r L a y o u t .WEST ) ; p a n e l . add ( new But ton ( E ) , B o r d e r L a y o u t . EAST ) ; f r a m e . add ( p a n e l ) ; f r a m e . pack ( ) ; frame . s e t V i s i b l e ( true ) ;

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

124 / 379

Java

Cours 4

Gestionnaires de pr esentation (FlowLayout)


Frame f r a m e = new Frame ( Ma f r a m e ) ; P a n e l p a n e l = new P a n e l ( ) ; // p a n e l . s e t L a y o u t ( new F l o w L a y o u t ( ) ) ; p a n e l . add ( new But ton ( b1 ) ) ; p a n e l . add ( new But ton ( b2 ) ) ; p a n e l . add ( new But ton ( b3 ) ) ; p a n e l . add ( new But ton ( b4 ) ) ; f r a m e . add ( p a n e l ) ; f r a m e . pack ( ) ; frame . s e t V i s i b l e ( true ) ;

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

125 / 379

Java

Cours 4

Gestionnaires de pr esentation (Composition)


Frame f r a m e = new Frame ( Ma f r a m e ) ; P a n e l p a n e l = new P a n e l ( ) ; p a n e l . s e t L a y o u t ( new B o r d e r L a y o u t ( ) ) ; p a n e l . add ( new L a b e l ( North ) , B o r d e r L a y o u t .NORTH) ; p a n e l . add ( new L a b e l ( South ) , B o r d e r L a y o u t . SOUTH ) ; P a n e l p a n e l C e n t e r = new P a n e l ( ) ; p a n e l C e n t e r . s e t L a y o u t ( new G r i d L a y o u t ( 2 , 2 ) ) ; f o r ( i n t i = 0 ; i < 4 ; i ++) p a n e l C e n t e r . add ( new Button ( B +i ) ) ; p a n e l . add ( p a n e l C e n t e r , B o r d e r L a y o u t . CENTER ) ; f r a m e . add ( p a n e l ) ; f r a m e . pack ( ) ; frame . s e t V i s i b l e ( true ) ;

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

126 / 379

Java

Cours 4

Sans gestionnaire de pr esentation


Frame f r a m e = new Frame ( Ma f r a m e ) ; P a n e l pane = new P a n e l ( ) ; pane . s e t L a y o u t ( n u l l ) ; But ton b1 = new But ton ( B1 ) ; But ton b2 = new But ton ( B2 ) ; But ton b3 = new But ton ( B3 ) ; pane . add ( b1 ) ; pane . add ( b2 ) ; pane . add ( b3 ) ; b1 . s e t B o u n d s ( 5 , 5 , 5 0 , 5 0 ) ; b2 . s e t B o u n d s ( 6 0 , 3 0 , 5 0 , 5 0 ) ; b3 . s e t B o u n d s ( 1 1 5 , 6 0 , 5 0 , 5 0 ) ; f r a m e . s e t P r e f e r r e d S i z e ( new D i m e n s i o n ( 1 8 5 , 1 5 0 ) ) ; f r a m e . add ( pane ) ; f r a m e . pack ( ) ; frame . s e t V i s i b l e ( true ) ;

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

127 / 379

Java

Cours 4

enements Ev`

Un ev` enement a lieu quand lutilisateur agit sur linterface graphique (clic de souris, bouton press e, s election dans une liste, ...) ; Un ev` enement est une instance dune classe qui etend AWTEvent ; Les ev` enements sont emis par les composants ; Les composants transmettent les ev` enements ` a des observateurs ; Un observateur impl emente une extension de EventListener ; Les m ethodes de linterface permettent de recevoir les ev` enements ; Les m ethodes add*Listener dun composant permettent dabonner un observateur aux ev` enements emis par ce composant.

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

128 / 379

Java

Cours 4

enements Ev`
Exemple :
p u b l i c c l a s s M y A c t i o n L i s t e n e r implements A c t i o n L i s t e n e r { p u b l i c void a c t i o n P e r f o r m e d ( Action Event e ) { System . o u t . p r i n t l n ( C l i c ! ! ) ; } } But ton b = new But ton ( B ) ; b . add A c t i o n L i s t e n e r ( new M y A c t i o n L i s t e n e r ( ) ) ; p a n e l . add ( b ) ;

Remarque : ActionListener est une extension de linterface EventListener ActionEvent est une extension de linterface AWTEvent

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

129 / 379

Java

Cours 4

enements Source Ev`


p u b l i c c l a s s M y A c t i o n L i s t e n e r implements A c t i o n L i s t e n e r { public void actionPerformed ( ActionEvent e ) { System . o u t . p r i n t l n ( e . g e t S o u r c e ( ) / Soit b1, soit b2 / ) ; } } A c t i o n L i s t e n e r l i s t e n e r = new new M y A c t i o n L i s t e n e r ( ) ; But ton b1 = new But ton ( B1 ) ; b1 . a d d A c t i o n L i s t e n e r ( l i s t e n e r ) ; p a n e l . add ( b1 ) ; But ton b2 = new But ton ( B2 ) ; b2 . a d d A c t i o n L i s t e n e r ( l i s t e n e r ) ;

Exemple de sortie : java.awt.Button[button0,39,5,29x23,label=B2] java.awt.Button[button1,5,5,29x23,label=B1] java.awt.Button[button0,39,5,29x23,label=B2] java.awt.Button[button1,5,5,29x23,label=B1]


Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 130 / 379

Java

Cours 4

enements Souris Ev`


p u b l i c i n t e r f a c e MouseListener extends E v e n t L i s t e n e r { p u b l i c v o i d m o u s e C l i c k e d ( MouseEvent e ) ; p u b l i c v o i d m o u s e P r e s s e d ( MouseEvent e ) ; p u b l i c v o i d m o u s e R e l e a s e d ( MouseEvent e ) ; p u b l i c v o i d m o u s e E n t e r e d ( MouseEvent e ) ; p u b l i c v o i d m o u s e E x i t e d ( MouseEvent e ) ; } p u b l i c i n t e r f a c e MouseMotionListener extends E v e n t L i s t e n e r { p u b l i c v o i d mouseDragged ( MouseEvent e ) ; p u b l i c v o i d mouseMoved ( MouseEvent e ) ; } p u b l i c i n t e r f a c e MouseWheelListener extends E v e n t L i s t e n e r { p u b l i c v o i d mouseWheelMoved ( MouseWheelEvent e ) ; }

Les ev` enements souris sont observables sur tous les composants
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 131 / 379

Java

Cours 4

enements Souris Ev`


Impl ementation de linterface MouseListener :
p u b l i c c l a s s S i m p l e M o u s e L i s t e n e r implements M o u s e L i s t e n e r { p u b l i c v o i d m o u s e C l i c k e d ( MouseEvent e ) { System . o u t . p r i n t l n ( e . getX ()+ +e . getY ( ) ) ; } public public public public } void void void void m o u s e P r e s s e d ( MouseEvent e ) { m o u s e R e l e a s e d ( MouseEvent e ) { m o u s e E n t e r e d ( MouseEvent e ) { m o u s e E x i t e d ( MouseEvent e ) { } } } }

Abonnement de lobservateur au composant :


Frame f r a m e = new Frame ( Ma f r a m e ) ; f r a m e . a d d M o u s e L i s t e n e r ( new S i m p l e M o u s e L i s t e n e r ( ) ) ; frame . s e t V i s i b l e ( true ) ;
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 132 / 379

Java

Cours 4

enements Clavier Ev`


p u b l i c i n t e r f a c e K e y L i s t e n e r extends E v e n t L i s t e n e r { p u b l i c v o i d keyTyped ( KeyEvent e ) ; p u b l i c v o i d k e y P r e s s e d ( KeyEvent e ) ; p u b l i c v o i d k e y R e l e a s e d ( KeyEvent e ) ; }

Exemple dimpl ementation :


p u b l i c c l a s s S i m p l e K e y L i s t e n e r implements K e y L i s t e n e r { p u b l i c v o i d keyTyped ( KeyEvent e ) { } p u b l i c v o i d k e y P r e s s e d ( KeyEvent e ) { System . o u t . p r i n t l n ( e . g e t K e y C h a r ( ) ) ; } p u b l i c v o i d k e y R e l e a s e d ( KeyEvent e ) { } }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

133 / 379

Java

Cours 4

enements Fen Ev` etre


p u b l i c i n t e r f a c e WindowListener extends E v e n t L i s t e n e r { p u b l i c v o i d windowOpened ( WindowEvent e ) ; p u b l i c v o i d w i n d o w C l o s i n g ( WindowEvent e ) ; p u b l i c v o i d w i n d o w C l o s e d ( WindowEvent e ) ; p u b l i c v o i d w i n d o w I c o n i f i e d ( WindowEvent e ) ; p u b l i c v o i d w i n d o w D e i c o n i f i e d ( WindowEvent e ) ; p u b l i c v o i d w i n d o w A c t i v a t e d ( WindowEvent e ) ; p u b l i c v o i d w i n d o w D e a c t i v a t e d ( WindowEvent e ) ; } p u b l i c i n t e r f a c e WindowStateListener extends E v e n t L i s t e n e r { p u b l i c v o i d w in dowStateChanged ( WindowEvent e ) ; } p u b l i c i n t e r f a c e WindowFocusListener extends E v e n t L i s t e n e r { p u b l i c v o i d w i n d o w G a i n e d F o c u s ( WindowEvent e ) ; p u b l i c v o i d w i n d o w L o s t F o c u s ( WindowEvent e ) ; }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 134 / 379

Java

Cours 4

enements Adapteurs Ev`


Un adapteur est une classe qui impl emente un observateur en associant un corps vide ` a chacune des m ethodes. Pour eviter dimpl ementer toutes les m ethodes dun observateur, on peut etendre ladapteur et red enir certaines de ses m ethodes.
p u b l i c c l a s s S i m p l e W i n d o w L i s t e n e r implements W i n d o w L i s t e n e r { p u b l i c v o i d windowOpened ( WindowEvent e ) { } p u b l i c v o i d w i n d o w C l o s i n g ( WindowEvent e ) { System . e x i t ( 0 ) ; } p u b l i c v o i d w i n d o w C l o s e d ( WindowEvent e ) { } p u b l i c v o i d w i n d o w I c o n i f i e d ( WindowEvent e ) { } p u b l i c v o i d w i n d o w D e i c o n i f i e d ( WindowEvent e ) { } p u b l i c v o i d w i n d o w A c t i v a t e d ( WindowEvent e ) { } p u b l i c v o i d w i n d o w D e a c t i v a t e d ( WindowEvent e ) { } }

est equivalent ` a
p u b l i c c l a s s S i m p l e W i n d o w L i s t e n e r e x t e n d s WindowAdapter { p u b l i c v o i d w i n d o w C l o s i n g ( WindowEvent e ) { System . e x i t ( 0 ) ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 135 / 379

Java

Cours 4

enements Adapteurs et classes anonymes Ev`

Extension dun adapteur en classe anonyme :


Frame f r a m e = new Frame ( Ma f r a m e ) ; f r a m e . a d d W i n d o w L i s t e n e r ( new WindowAdapter ( ) { p u b l i c v o i d w i n d o w C l o s i n g ( WindowEvent e ) { System . e x i t ( 0 ) ; } }); frame . s e t V i s i b l e ( true ) ;

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

136 / 379

Java

Cours 4

Exemple Calculette
p u b l i c c l a s s C a l c u l e t t e e x t e n d s Frame { p r i v a t e T e x t F i e l d number1 , number2 ; private Label r e s u l t ; public Calculette () { s e t P r e f e r r e d S i z e ( new D i m e n s i o n ( 2 0 0 , 8 0 ) ) ; P a n e l p = new P a n e l ( ) ; number1 = new T e x t F i e l d ( 5 ) ; number2 = new T e x t F i e l d ( 5 ) ; r e s u l t = new L a b e l ( 0 ) ; But ton b = new Button ( Add ) ; b . a d d A c t i o n L i s t e n e r ( new B o u t o n L i s t e n e r ( ) ) ; p . add ( number1 ) ; p . add ( number2 ) ; p . add ( r e s u l t ) ; p . add ( b ) ; add ( p ) ; pack ( ) ; }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 137 / 379

Java

Cours 4

Exemple Calculette
Suite de la classe Calculette :
p u b l i c c l a s s C a l c u l e t t e e x t e n d s Frame { p r i v a t e T e x t F i e l d number1 , number2 ; private Label r e s u l t ; .... p r i v a t e c l a s s B o u t o n L i s t e n e r implements A c t i o n L i s t e n e r { public void actionPerformed ( ActionEvent e ) { i n t v1 = I n t e g e r . p a r s e I n t ( number1 . g e t T e x t ( ) ) ; i n t v2 = I n t e g e r . p a r s e I n t ( number2 . g e t T e x t ( ) ) ; r e s u l t . s e t T e x t ( +(v1+v2 ) ) ; } } }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

138 / 379

Java

Cours 4

Exemple Calculette

La m ethode main :
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) { C a l c u l e t t e c a l c u l e t t e = new C a l c u l e t t e ( ) ; c a l c u l e t t e . s e t V i s i b l e ( true ) ; c a l c u l e t t e . a d d W i n d o w L i s t e n e r ( new WindowAdapter ( ) { p u b l i c v o i d w i n d o w C l o s i n g ( WindowEvent e ) { System . e x i t ( 0 ) ; } }); }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

139 / 379

Java

Cours 4

Cr eation de son composant


Il sut d etendre la classe Component
p u b l i c c l a s s MyComponent e x t e n d s Component { p u b l i c MyComponent ( ) { s e t P r e f e r r e d S i z e ( new D i m e n s i o n ( 2 0 0 , 2 0 0 ) ) ; } public void paint ( Graphics g ) { Dimension s i z e = g e t S i z e ( ) ; g . setColor ( Color . white ) ; g . f i l l O v a l ( 0 , 0 , s i z e . w idth , s i z e . h e i g h t ) ; g . setColor ( Color . blue ) ; g . d r a w L i n e ( 0 , s i z e . h e i g h t / 2 , s i z e . w idt h , s i z e . h e i g h t / 2 ) ; g . drawLine ( s i z e . width /2 , 0 , s i z e . width /2 , s i z e . h e i g h t ) ; g . setColor ( Color . red ) ; g . drawOval ( 0 , 0 , s i z e . widt h , s i z e . h e i g h t ) ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 140 / 379

Java

Cours 4

Cr eation de son composant


Frame f r a m e = new Frame ( Ma f r a m e ) ; f r a m e . add ( new MyComponent ( ) ) ; f r a m e . pack ( ) ; f r a m e . a d d W i n d o w L i s t e n e r ( new WindowAdapter ( ) { p u b l i c v o i d w i n d o w C l o s i n g ( WindowEvent e ) { System . e x i t ( 0 ) ; } }); frame . s e t V i s i b l e ( true ) ;

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

141 / 379

Java

Cours 4

Cr eation de son composant


Changement de la couleur du disque quand on clique sur le composant :
p u b l i c c l a s s MyComponent e x t e n d s Component { private Color color = Color . white ; p u b l i c MyComponent ( ) { s e t P r e f e r r e d S i z e ( new D i m e n s i o n ( 2 0 0 , 2 0 0 ) ) ; a d d M o u s e L i s t e n e r ( new MyMouseAdapter ( ) ) ; } public void paint ( Graphics g ) { g . setColor ( color ); g . f i l l O v a l ( 0 , 0 , s i z e . w idth , s i z e . h e i g h t ) ; ... } ... }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 142 / 379

Java

Cours 4

Cr eation de son composant


Changement de la couleur du disque quand on clique sur le composant :
p u b l i c c l a s s MyComponent e x t e n d s Component { private Color color = Color . white ; ... p r i v a t e c l a s s MyMouseAdapter e x t e n d s MouseAdapter { p u b l i c v o i d m o u s e C l i c k e d ( MouseEvent e ) { i f ( c o l o r == C o l o r . w h i t e ) c o l o r = Color . gray ; else co lo r = Color . white ; repaint () ; } } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 143 / 379

Java

Cours 4

Swing
Swing est plus riche en composants que AWT Swing propose des composants plus jolis (look and feel) Swing respecte larchitecture Mod` ele-Vue-Contr oleur (MVC). Exemple dutilisation de Swing :
public c l a s s HelloWorld { p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) { JFrame f r a m e = new JFrame ( H e l l o World ! ) ; f r a m e . s e t D e f a u l t C l o s e O p e r a t i o n ( JFrame . DISPOSE ON CLOSE ) ; J L a b e l l a b e l = new J L a b e l ( H e l l o , World ! ) ; f r a m e . g e t C o n t e n t P a n e ( ) . add ( l a b e l ) ; f r a m e . pack ( ) ; frame . s e t L o c a t i o n R e l a t i v e T o ( n u l l ) ; frame . s e t V i s i b l e ( true ) ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 144 / 379

Java

Cours 4

Relations entre Swing et AWT

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

145 / 379

Java

Cours 4

Les composants de Swing


El ements de base : JButton, JCheckBox, JComboBox, JMenu, JList, JRadioButton, JSlider, JSpinner, JTextField, JPasswordField, JColorChooser, JEditorPane, JTextPane, JFileChooser, JTable, JTextArea, JTree, JLabel, JProgressBar, JSeparator, JToolTip... Conteneurs de haut niveau : JApplet, JDialog, JFrame... Conteneurs : JPanel, JScrollPane, JSplitPane, JToolBar, JTabbedPane, JInternalFrame, JLayeredPane...

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

146 / 379

Java

Cours 4

Look and feel

GTKLookAndFeel

MotifLookAndFeel

WindowsLookAndFeel
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 147 / 379

Java

Cours 4

Look and feel


Au d ebut du programme :
try { UIManager . s e t L o o k A n d F e e l ( com . sun . j a v a . s w i n g . p l a f . g t k . GTKLookAndFeel ) ; } catch ( E x c e p t i o n e ) { System . o u t . p r i n t l n ( E r r o r s e t t i n g LookAndFeel : + e ) ; }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

148 / 379

Java

Cours 4

Cr eation de son composant Swing


p u b l i c c l a s s MySwingComponent e x t e n d s J P a n e l { p u b l i c MyComponentSwing ( ) { s e t P r e f e r r e d S i z e ( new D i m e n s i o n ( 2 0 0 , 2 0 0 ) ) ; } p u b l i c void paintComponent ( G r a p h i c s g ) { s u p e r . paintComponent ( g ) ; Dimension s i z e = g e t S i z e ( ) ; g . setColor ( Color . white ) ; g . f i l l O v a l ( 0 , 0 , s i z e . w idth , s i z e . h e i g h t ) ; g . setColor ( Color . blue ) ; g . d r a w L i n e ( 0 , s i z e . h e i g h t / 2 , s i z e . w idt h , s i z e . h e i g h t / 2 ) ; g . drawLine ( s i z e . width /2 , 0 , s i z e . width /2 , s i z e . h e i g h t ) ; g . setColor ( Color . red ) ; g . drawOval ( 0 , 0 , s i z e . widt h , s i z e . h e i g h t ) ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 149 / 379

Java

Cours 4

Remarques sur Swing

paint appelle paintComponent, paintBorder, paintChildren Red enir paintComponent pour changer lachage dun composant Pour redessiner le composant, appeler repaint (pas paint) Dans paintComponent, commencer par super.paintComponent(g) Ne pas m elanger des composants de Swing et de AWT

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

150 / 379

Java

Cours 5

R esum e des cours pr ec edents


Premier cours : Objets, classes, instances, r ef erences D enir et instancier une classe Deuxi` eme cours : Description et impl ementation dinterfaces Transtypage (vers le haut et vers le bas) Troisi` eme cours : Extension de classe Red enition de m ethodes et polymorphisme Classes et m ethodes abstraites La classe Object
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 151 / 379

Java

Cours 5

Surcharge de m ethodes
Dans une classe, plusieurs m ethodes peuvent avoir le m eme nom. La m ethode est choisie par le compilateur de la fa con suivante :
Le nombre de param` etres doit correspondre ; Les aectations des param` etres doivent etre valides ; Parmi ces m ethodes, le compilateur choisit la plus sp ecialis ee.
class Additionneur { public static int additionner ( int a , int b) { System . o u t . p r i n t l n ( e n t i e r ) ; r e t u r n a+b ; } p u b l i c s t a t i c double a d d i t i o n n e r ( double a , double b ) { System . o u t . p r i n t l n ( f l o t t a n t ) ; r e t u r n a+b ; } } i n t i = 1; double d = 2 . 2 ; d o u b l e r 1 = A d d i t i o n n e u r . a d d i t i o n n e r ( d , d ) ; // ottant d o u b l e r 2 = A d d i t i o n n e u r . a d d i t i o n n e r ( i , d ) ; // ottant i n t r 3 = A d d i t i o n n e u r . a d d i t i o n n e r ( i , i ) ; // entier
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 152 / 379

Java

Cours 5

Surcharge de m ethodes
Dans une classe, plusieurs m ethodes peuvent avoir le m eme nom. La m ethode est choisie par le compilateur de la fa con suivante :
Le nombre de param` etres doit correspondre ; Les aectations des param` etres doivent etre valides ; Parmi ces m ethodes, le compilateur choisit la plus sp ecialis ee.
class Afficheur { s t a t i c void A f f i c h e r ( Object o ) System . o u t . p r i n t l n ( O b j e c t } s t a t i c void A f f i c h e r ( String s ) System . o u t . p r i n t l n ( S t r i n g } } { : +o ) ; { : +s ) ;

S t r i n g s = m e s s a g e ; Object o = s ; A f f i c h e u r . A f f i c h e r ( s ) ; // String : message A f f i c h e u r . A f f i c h e r ( o ) ; // Object : message


Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 153 / 379

Java

Cours 5

Surcharge de m ethodes et extension


Attention :
c l a s s C {} c l a s s D e x t e n d s C {} class A { p u b l i c v o i d method (D d ) { System . o u t . p r i n t l n ( D ) ; } } c l a s s B extends A { p u b l i c v o i d method (C c ) { System . o u t . p r i n t l n ( C ) ; } } B b = new B ( ) ; b . method ( new C ( ) ) ; // ache C b . method ( new D ( ) ) ; // ache D

En Java, il ny a pas de contravariance lors de lextension (la m ethode de B ne red enit pas la m ethode de A m eme si ses arguments sont moins sp ecialis es)
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 154 / 379

Java

Cours 5

Covariance
class A { p u b l i c O b j e c t g e t ( ) { r e t u r n O b j e c t ; } } c l a s s B extends A { p u b l i c S t r i n g get ( ) { return S t r i n g ; } } B b = new B ( ) ; A a = b ; String s = b . get ( ) ; System . o u t . p r i n t l n ( s ) ; // Object o = a . get ( ) ; // System . o u t . p r i n t l n ( o ) ; // a = new A ( ) ; o = a . get ( ) ; System . o u t . p r i n t l n ( o ) ; //

Ache String Le type de retour est Object (et pas String) Ache String

Ache Object

Covariance : on peut modier le type de la valeur retourn ee par une m ethode que lon red enit si le nouveau type etend lancien
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 155 / 379

Java

Cours 5

Types param etr es Pourquoi ?


La classe Pile :
public class Pile { private Object [ ] p i l e ; private int t a i l l e ; p u b l i c P i l e ( ) { p i l e = new O b j e c t [ 1 0 0 ] ; public void empiler ( Object o ) { p i l e [ t a i l l e ] = o ; t a i l l e ++; } public Object d e p i l e r () { t a i l l e ; O b j e c t o = p i l e [ t a i l l e ] ; return o ; } } t a i l l e = 0; }

p i l e [ t a i l l e ]= n u l l ;

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

156 / 379

Java

Cours 5

Types param etr es Pourquoi ?


Premier probl` eme :
P i l e p = new P i l e ( ) ; S t r i n g s = t r u c ; p . empiler ( s ); // Ok car String etend Object s = ( S t r i n g ) p . d e p i l e r ( ) ; // Transtypage obligatoire

Deuxi` eme probl` eme :


P i l e p = new P i l e ( ) ; I n t e g e r i = new I n t e g e r ( 2 ) ; p . empiler ( i ); // Ok car Integer etend Object S t r i n g s = ( S t r i n g ) p . d e p i l e r ( ) ; // Erreur ` a lex ecution (String != Integer)

Solution : pr eciser le type des el ements autoris es dans la pile


P i l e < S t r i n g > p = new P i l e < S t r i n g > ( ) ; S t r i n g s = t r u c ; p . empiler ( s ); // Ok car s est de type String S t r i n g s = p . d e p i l e r ( ) ; // Ok car la pile ne contient que des String
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 157 / 379

Java

Cours 5

Types param etr es Classes param etr ees


p u b l i c c l a s s P i l e <T> { private Object [ ] p i l e ; public int t a i l l e ; (En Java, impossible de d enir de tableau de T)

p u b l i c P i l e ( ) { p i l e = new O b j e c t [ 1 0 0 ] ; p u b l i c v o i d e m p i l e r (T o ) { p i l e [ t a i l l e ] = o ; t a i l l e ++; } public T depiler () { t a i l l e ; T e = p i l e [ t a i l l e ] ; r e t u r n (T) e ; } }

t a i l l e = 0; }

p i l e [ t a i l l e ]= n u l l ;

En Java, les types param etr es ajoutent des v erications de type et des transtypages automatiques lors de la compilation mais ne modient pas le bytecode g en er e.
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 158 / 379

Java

Cours 5

Boxing et unboxing
Comment obtenir une pile dentiers ?
P i l e < i n t > p = new P i l e < i n t > ( ) ; Impossible : int nest pas le nom dune classe

Il faut utiliser la classe demballage Integer associ e au type simple int :


P i l e < I n t e g e r > p = new P i l e < I n t e g e r > ( ) ; int i = 2; I n t e g e r j = new I n t e g e r ( i ) ; (empaquetage du int dans un Integer) p . empiler ( j ); Integer k = p. depiler (); i n t l = j . i n t V a l u e ( ) ; (d eballage du int pr esent dans le Integer)

Depuis Java 5, autoboxing et auto-unboxing :


P i l e < I n t e g e r > p = new P i l e < I n t e g e r > ( ) ; int i = 2; p . e m p i l e r ( i ) ; (empaquetage du int dans un Integer) i n t l = p . d e p i l e r ( ) ; (d eballage du int pr esent dans le Integer)

(Attention : des allocations sont eectu ees sans new dans le code)
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 159 / 379

Java

Cours 5

Rappel : Les types primitifs

byte short int long oat double char boolean

entier entier entier entier otant otant caract` ere boolean

8 bits 16 bits 32 bits 64 bits 32 bits 64 bits 16 bits 1 bit

-128 ` a 127 -32768 ` a 32767 231 ` a 231 1 263 ` a 263 1

caract` eres Unicode false ou true

0 0 0 0 0.0 0.0 \u0000 false

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

160 / 379

Java

Cours 5

Classes demballage
La classe Number : public abstract int intValue () public abstract long longValue () public abstract oat oatValue () public abstract double doubleValue () public byte byteValue() public short shortValue() Les classes demballage qui etendent Number : Byte : public Byte(byte b) Short : public Short(short s) Integer : public Integer(int i) Long : public Long(long l) Float : public Float(oat f) Double : public Double(double d)
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 161 / 379

Java

Cours 5

Classes demballage
La classe Boolean : public Boolean(bool b) public boolean booleanValue() La classe Character : public Character(char c) public char charValue() public static boolean isLowerCase (char ch) public static boolean isUpperCase (char ch) public static boolean isTitleCase (char ch) public static boolean isDened (char ch) public static boolean isDigit (char ch) public static boolean isLetter (char ch) public static boolean isLetterOrDigit (char ch) public static char toLowerCase (char ch) public static char toUpperCase (char ch) public static char toTitleCase (char ch)
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 162 / 379

Java

Cours 5

Types param etr es Impl ementation


p u b l i c i n t e r f a c e Comparable<T> { (Interface Java) p u b l i c i n t compareTo (T o ) ; } c l a s s C a r t e implements Comparable< C a r t e > { public int coul ; public int val ; public Carte ( int c , int v ) { coul = c ; val = v ; } p u b l i c i n t compareTo ( C a r t e c ) { i n t cc = c o u l c . c o u l ; i f ( c c !=0) r e t u r n c c ; else return val c . val ; } p u b l i c S t r i n g t o S t r i n g ( ) { r e t u r n [ +c o u l+ , +v a l+ ] ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 163 / 379

Java

Cours 5

Types param etr es Condition sur les param` etres


c l a s s S o r t e d A r r a y <T e x t e n d s Comparable <T> > { p r i v a t e Object [ ] tab ; public int taille ; t a i l l e = 0; }

p u b l i c S o r t e d A r r a y ( ) { t a b = new O b j e c t [ 1 0 0 ] ; p u b l i c T g e t ( i n t p ) { r e t u r n (T) t a b [ p ] ; }

p u b l i c v o i d add (T e ) { int p = 0; w h i l e ( p < t a i l l e && e . compareTo ( g e t ( p ) ) >0) p++; f o r ( i n t i = t a i l l e ; i > p ; i ) t a b [ i ] = t a b [ i 1 ] ; tab [ p ] = e ; t a i l l e ++; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 164 / 379

Java

Cours 5

M ethodes param etr ees et surcharge


c l a s s Tools { s t a t i c boolean i s S o r t e d ( S t r i n g [ ] t ) { f o r ( i n t i = 0 ; i < t . l e n g t h 1; i ++) i f ( t [ i ] . l e n g t h () > t [ i +1]. l e n g t h ( ) ) return f a l s e ; return true ; } s t a t i c <T e x t e n d s Comparable <T>> boolean i s S o r t e d (T [ ] t ) { f o r ( i n t i = 0 ; i < t . l e n g t h 1; i ++) i f ( t [ i ] . compareTo ( t [ i +1]) > 0 ) r e t u r n f a l s e ; return true ; } }

Exemple 1 :
C a r t e [ ] t a b = new C a r t e [ 3 ] ; t a b [ 0 ] = new C a r t e ( 1 , 2 ) ; t a b [ 1 ] = new C a r t e ( 2 , 3 ) ; t a b [ 2 ] = new C a r t e ( 2 , 4 ) ; System . o u t . p r i n t l n ( T o o l s . i s S o r t e d ( t a b ) ) ;
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 165 / 379

Java

Cours 5

M ethodes param etr ees et surcharge


c l a s s Tools { s t a t i c boolean i s S o r t e d ( S t r i n g [ ] t ) { f o r ( i n t i = 0 ; i < t . l e n g t h 1; i ++) i f ( t [ i ] . l e n g t h () > t [ i +1]. l e n g t h ( ) ) return f a l s e ; return true ; } s t a t i c <T e x t e n d s Comparable <T>> boolean i s S o r t e d (T [ ] t ) { f o r ( i n t i = 0 ; i < t . l e n g t h 1; i ++) i f ( t [ i ] . compareTo ( t [ i +1]) > 0 ) r e t u r n f a l s e ; return true ; } }

Exemple 2 :
S t r i n g [ ] t a b = new S t r i n g [ 3 ] ; t a b [ 0 ] = t o t o ; t a b [ 1 ] = t r u c ; t a b [ 2 ] = abc ; System . o u t . p r i n t l n ( T o o l s . i s S o r t e d ( t a b ) ) ;
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 166 / 379

Java

Cours 5

M ethodes param etr ees et surcharge


c l a s s Tools { s t a t i c boolean i s S o r t e d ( S t r i n g [ ] t ) { f o r ( i n t i = 0 ; i < t . l e n g t h 1; i ++) i f ( t [ i ] . l e n g t h () > t [ i +1]. l e n g t h ( ) ) return f a l s e ; return true ; } s t a t i c <T e x t e n d s Comparable <T>> boolean i s S o r t e d (T [ ] t ) { f o r ( i n t i = 0 ; i < t . l e n g t h 1; i ++) i f ( t [ i ] . compareTo ( t [ i +1]) > 0 ) r e t u r n f a l s e ; return true ; } }

Exemple 3 :
O b j e c t [ ] t a b = new S t r i n g [ 3 ] ; t a b [ 0 ] = t o t o ; t a b [ 1 ] = t r u c ; t a b [ 2 ] = abc ; System . o u t . p r i n t l n ( T o o l s . i s S o r t e d ( t a b ) ) ; Erreur de compilation
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 167 / 379

Java

Cours 5

Les it erateurs
p u b l i c i n t e r f a c e I t e r a b l e <T> { (Interface Java) p u b l i c I t e r a t o r <T> i t e r a t o r ( ) ; } p u b l i c i n t e r f a c e I t e r a t o r <T> { (Interface Java) p u b l i c b o o le a n h a s N e x t ( ) ; public T next ( ) ; p u b l i c v o i d remove ( ) ; }

Exemple dutilisation :
s t a t i c <T> v o i d p r i n t C o l l e c t i o n ( I t e r a b l e <T> t ) { I t e r a t o r <T> i t = t . i t e r a t o r ( ) ; while ( i t . hasNext ( ) ) { T e = i t . next ( ) ; System . o u t . p r i n t l n ( e ) ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 168 / 379

Java

Cours 5

Les it erateurs impl ementation


c l a s s S o r t e d A r r a y I t e r a t o r <T e x t e n d s Comparable <T>> i m p l e m e n t s I t e r a t o r <T> { i n t pos ; S o r t e d A r r a y <T> s a ; S o r t e d A r r a y I t e r a t o r ( S o r t e d A r r a y <T> s a ) { pos = 0 ; t h i s . sa = sa ; } p u b l i c b o o le a n h a s N e x t ( ) { r e t u r n p o s < s a . t a i l l e ; } public T next () { T e = s a . g e t ( p o s ) ; p o s++; return e ; } p u b l i c v o i d remove ( ) { . . . } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 169 / 379

Java

Cours 5

Les it erateurs impl ementation


c l a s s S o r t e d A r r a y <T e x t e n d s Comparable <T>> i m p l e m e n t s I t e r a b l e <T> p r i v a t e Object [ ] tab ; public int taille ; t a i l l e = 0; }

p u b l i c S o r t e d A r r a y ( ) { t a b = new O b j e c t [ 1 0 0 ] ; p u b l i c T g e t ( i n t p ) { r e t u r n (T) t a b [ p ] ; } ... p u b l i c S o r t e d A r r a y I t e r a t o r <T> i t e r a t o r ( ) { r e t u r n new S o r t e d A r r a y I t e r a t o r ( t h i s ) ; } }


Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet

29 mai 2012

170 / 379

Java

Cours 5

Les it erateurs utilisation


Exemple de m ethode g en erique :
s t a t i c <T> v o i d p r i n t C o l l e c t i o n ( I t e r a b l e <T> t ) { I t e r a t o r <T> i t = t . i t e r a t o r ( ) ; while ( i t . hasNext ( ) ) { T e = i t . next ( ) ; System . o u t . p r i n t l n ( e ) ; } }

Exemple dutilisation :
S o r t e d A r r a y <C a r t e > a = new S o r t e d A r r a y <C a r t e > ( ) ; a . add ( new C a r t e ( 1 , 2 ) ) ; a . add ( new C a r t e ( 2 , 1 ) ) ; a . add ( new C a r t e ( 1 , 4 ) ) ; Tools . p r i n t C o l l e c t i o n ( a ) ;

Java (5 et plus) et les it erateurs :


f o r ( C a r t e c : a ) { System . o u t . p r i n t l n ( c ) ; }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 171 / 379

Java

Cours 5

Types param etr es Plusieurs param` etres


Il est possible davoir plusieurs param` etres :
p u b l i c c l a s s P a i r <A , B> { public A f i r s t ; public B second ; p u b l i c P a i r (A f , B s ) { f i r s t = f ; s e c o n d = s ; } p u b l i c s t a t i c <A , B> P a i r <A , B> m a k e P a i r (A f , B s ) { r e t u r n new P a i r <A , B>( f , s ) ; } }

Exemple dutilisation de la classe Pair :


P a i r < I n t e g e r , I n t e g e r > p = new P a i r < I n t e g e r , I n t e g e r > ( 2 , 3 ) ; P a i r <I n t e g e r , I n t e g e r > p = P a i r . m a k e P a i r ( 2 , 3 ) ; P a i r <I n t e g e r , I n t e g e r > p = P a i r . m a k e P a i r ( 2 . 5 , 3 ) ; ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: Types incompatibles : Pair<Integer, Integer> != Pair<Double, Integer>
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 172 / 379

Java

Cours 5

Types param etr es ? super


Probl` eme :
c l a s s C a r t e implements Comparable <C a r t e > { . . . } c l a s s J o l i e C a r t e extends Carte { . . . } c l a s s S o r t e d A r r a y <T e x t e n d s Comparable<T> > { ... } S o r t e d A r r a y < J o l i e C a r t e > s = new S o r t e d A r r a y <J o l i e C a r t e > ( ) ; :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // Erreur : JolieCarte nimpl emente pas Comparable<JolieCarte>

Solution :
c l a s s S o r t e d A r r a y <T e x t e n d s Comparable <? s u p e r T> > { ... } S o r t e d A r r a y < J o l i e C a r t e > s = new S o r t e d A r r a y < J o l i e C a r t e > ( ) ; // Ok : JolieCarte impl emente Comparable<Carte>

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

173 / 379

Java

Cours 5

Types param etr es ? super


Rien ne change dans la classe SortedArray :
c l a s s S o r t e d A r r a y <T e x t e n d s Comparable <? s u p e r T>> ... p u b l i c T g e t ( i n t p ) { r e t u r n (T) t a b [ p ] ; } {

p u b l i c v o i d add (T e ) { int p = 0; w h i l e ( p < t a i l l e && e . compareTo ( g e t ( p ) ) >0) p++; f o r ( i n t i = t a i l l e ; i > p ; i ) t a b [ i ] = t a b [ i 1 ] ; tab [ p ] = e ; t a i l l e ++; } ... }

Le type du param` etre de e.compareTo est ? super T La m ethode get(p) retourne un param` etre de type T T est compatible avec ? super T => Les types sont corrects.
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 174 / 379

Java

Cours 5

Types param etr es ? extends


Probl ematique :
c l a s s C a r t e implements Comparable <C a r t e > { . . . } c l a s s J o l i e C a r t e extends Carte { . . . } c l a s s S o r t e d A r r a y <T e x t e n d s Comparable <? s u p e r T>> i m p l e m e n t s I t e r a b l e <T> { ... p u b l i c v o i d a d d A l l ( I t e r a b l e <T> c ) { f o r (T e : c ) add ( e ) ; } ... } S o r t e d A r r a y <C a r t e > c = new S o r t e d A r r a y <C a r t e > ( ) ; S o r t e d A r r a y < J o l i e C a r t e > j c = new S o r t e d A r r a y < J o l i e C a r t e > ( ) ;
::::::::::::::::

c . addAll ( jc ) ; // Erreur : SortedArray<JolieCarte> nimpl emente pas Iterable<Carte>


Programmation Orient ee Objet 29 mai 2012 175 / 379

Bertrand Estellon (DIL Aix-Marseille)

Java

Cours 5

Types param etr es ? extends


Solution :
c l a s s C a r t e implements Comparable <C a r t e > { . . . } c l a s s J o l i e C a r t e extends Carte { . . . } c l a s s S o r t e d A r r a y <T e x t e n d s Comparable <? s u p e r T>> i m p l e m e n t s I t e r a b l e <T> { ... p u b l i c v o i d a d d A l l ( I t e r a b l e <? e x t e n d s T> c ) { f o r (T e : c ) add ( e ) ; } ... } S o r t e d A r r a y <C a r t e > c = new S o r t e d A r r a y <C a r t e > ( ) ; S o r t e d A r r a y < J o l i e C a r t e > j c = new S o r t e d A r r a y < J o l i e C a r t e > ( ) ; c . a d d A l l ( j c ) ; // Ok : SortedArray<JolieCarte> impl emente Iterable<JolieCarte>

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

176 / 379

Java

Cours 5

Types param etr es ? extends


Explication :
c l a s s S o r t e d A r r a y <T e x t e n d s Comparable <? s u p e r T>> i m p l e m e n t s I t e r a b l e <T> { ... p u b l i c v o i d a d d A l l ( I t e r a b l e <? e x t e n d s T> c ) { I t e r a t o r <? e x t e n d s T> i t = c . i t e r a t o r ( ) ; while ( i t . hasNext ( ) ) { T e = i t . next ( ) ; add ( e ) ; } } ... }

Le retour de it.next() est de type ? extends T Il peut donc etre transtyp e (vers le haut) en T ? extends T est compatible avec T => Les types sont corrects.
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 177 / 379

Java

Cours 5

R esum e

Surcharge de m ethodes Covariance Boxing, unboxing et classes demballage Classes param etr ees Condition sur les param` etres M ethodes param etr ees It erateurs ? super et ? extends

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

178 / 379

Java

Cours 6

R esum e des cours pr ec edents


Premier cours : Objets, classes, instances, r ef erences D enir et instancier une classe Deuxi` eme cours : Description et impl ementation dinterfaces Transtypage (vers le haut et vers le bas) Troisi` eme cours : Extension de classes, red enition de m ethodes Classes et m ethodes abstraites Cinqui` eme cours : Surcharge de m ethodes Types param etr es
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 179 / 379

Java

Cours 6

Structures de donn ees Java


Des interfaces : Collection<V> : Groupe d el ements
List<V> : Liste d el ements ordonn es et accessibles via leur indice Set<V> : Ensemble d el ements uniques Queue<V> : Une le d el ements (FIFO) Deque<V> : Une le ` a deux bouts (FIFO-LIFO)

Map<K,V> : Ensemble de couples cl e-valeur. Il est pr ef erable dutiliser les interfaces pour typer les variables : L i s t < I n t e g e r > l = new A r r a y L i s t < I n t e g e r > ( ) ; (code qui utilise l) car on peut changer la structure de donn ees facilement : L i s t < I n t e g e r > l = new L i n k e d L i s t < I n t e g e r > ( ) ; (code qui utilise l et qui na pas ` a etre modi e)
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 180 / 379

Java

Cours 6

Les collections
Les m ethodes de linterface Collection<V> : boolean add(V e) boolean addAll(Collection<? extends V> c) void clear() boolean contains(Object o) boolean containsAll(Collection<?> c) boolean isEmpty() boolean remove(Object o) boolean removeAll(Collection<?> c) boolean retainAll(Collection<?> c) int size() Object[] toArray() <T> T[] toArray(T[] a)
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 181 / 379

Java

Cours 6

Les listes
Les m ethodes de linterface List<V> : void add(int index, V element) boolean addAll(int index, Collection<? extends V> c) V get(int index) int indexOf(Object o) int lastIndexOf(Object o) V remove(int index) int indexOf(Object o) V set(int index, V element) List<V> subList(int fromIndex, int toIndex) + les m ethodes de Collection<V>

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

182 / 379

Java

Cours 6

Les listes

Quelques impl ementations de linterface List<V> : ArrayList<V> : Tableau dont la taille varie dynamiquement. LinkedList<V> : Liste cha n ee. Vector<V> : Comme ArrayList mais synchronis e. Stack<V> : Pile (mais une impl ementation de Deque est pr ef erable).

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

183 / 379

Java

Cours 6

Les maps
Les m ethodes de linterface Map<K,V> : clear() boolean containsKey(Object key) boolean containsValue(Object value) Set<Map.Entry<K,V>> entrySet() V get(Object key) boolean isEmpty() Set<K> keySet() V put(K key, V value) void putAll(Map<? extends K,? extends V> m) V remove(Object key) int size() Collection<V> values()
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 184 / 379

Java

Cours 6

Les maps
Quelques impl ementations de linterface Map<K,V> : HashMap : table de hachage LinkedHashMap : table de hachage + listes chain ees TreeMap : arbre rouge-noir (Les el ements doivent etre comparables) Table de hachage :
John Smith 0 1 Lisa Smith +1-555-8976

Lisa Smith

872 873

John Smith

+1-555-1234

Sam Doe

998 999

Sam Doe

+1-555-5030

Calcul de lindice : int indice = key.hashcode() & (taille - 1) ; Calcul du hashcode : int hashcode() (m ethode de la classe Object)
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 185 / 379

Java

Cours 6

Les maps
Quelques impl ementations de linterface Map<K,V> : HashMap : table de hachage LinkedHashMap : table de hachage + listes chain ees TreeMap : arbre rouge-noir (Les el ements doivent etre comparables) Arbre rouge-noir :

Rechercher Ins erer Supprimer

Complexit e O (log n) O (log n) O (log n)

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

185 / 379

Java

Cours 6

Les maps
Quelques impl ementations de linterface Map<K,V> : HashMap : table de hachage LinkedHashMap : table de hachage + listes chain ees TreeMap : arbre rouge-noir (Les el ements doivent etre comparables) Arbre rouge-noir et interface Comparator : Map<Carte, Integer> m = new TreeMap<Carte, Integer>( new Comparator<Carte>() { public int compare(Carte o1, Carte o2) { ... }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 185 / 379

Java

Cours 6

Les ensembles

Set<V> ne contient que les m ethodes de Collection<V> Quelques impl ementations de linterface Set<V> : HashSet<V> : avec une HashMap. LinkedHashSet<V> : avec une LinkedHashMap. TreeSet<V> : avec une TreeMap.

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

186 / 379

Java

Cours 6

Les les

Les m ethodes de linterface Queue<V> : V element() boolean offer(V e) V peek() V poll() V remove() + les m ethodes de Collection<V>

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

187 / 379

Java

Cours 6

Les les ` a deux bouts (Deque)


Les m ethodes de linterface Deque<V> :
Premier el ement avec exception avec null addFirst(e) oerFirst(e) removeFirst() pollFirst() getFirst() peekFirst() Dernier el ement avec exception avec null addLast(e) oerLast(e) removeLast() pollLast() getLast() peekLast()

Ins erer Supprimer Consulter

Correspondance avec les m ethodes de Queue<V> :


Dans Queue add(e) oer(e) remove() poll() element() peek()
Bertrand Estellon (DIL Aix-Marseille)

Dans Deque addLast(e) oerLast(e) emoveFirst() pollFirst() getFirst() peekFirst()


29 mai 2012 188 / 379

Programmation Orient ee Objet

Java

Cours 6

Les les ` a deux bouts (Deque)

Quelques impl ementations de linterface Deque<V> : ArrayDeque<V> : avec un tableau dynamique. LinkedList<V> : avec une liste cha n ee.

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

189 / 379

Java

Cours 6

Les iterateurs
Linterface Collection<V> etend Iterable<V> :
C o l l e c t i o n < I n t e g e r > l = new A r r a y L i s t < I n t e g e r > ( ) ; l . add ( 1 ) ; l . add ( 2 ) ; l . add ( 1 ) ; for ( Integer i : l ) System . o u t . p r i n t ( i+ ) ; System . o u t . p r i n t l n ( ) ;

Sortie : 1 2 1
C o l l e c t i o n < I n t e g e r > l = new HashSet < I n t e g e r > ( ) ; l . add ( 1 ) ; l . add ( 2 ) ; l . add ( 1 ) ; for ( Integer i : l ) System . o u t . p r i n t ( i+ ) ; System . o u t . p r i n t l n ( ) ;

Sortie : 1 2

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

190 / 379

Java

Cours 6

Les iterateurs
Exemple avec une HashMap :
Map< S t r i n g , I n t e g e r > m = new HashMap< S t r i n g , I n t e g e r > ( ) ; m. p u t ( t o t o , 4 ) ; m. p u t ( aaa , 3 ) ; m. p u t ( bb , 2 ) ; f o r ( I n t e g e r i : m. v a l u e s ( ) ) System . o u t . p r i n t ( i+ ) ; System . o u t . p r i n t l n ( ) ; f o r ( S t r i n g k : m. k e y S e t ( ) ) System . o u t . p r i n t ( k+ ) ; System . o u t . p r i n t l n ( ) ;

Sortie : 3 4 2 aaa toto bb

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

191 / 379

Java

Cours 6

Exceptions

Tout programme peut etre confront e` a une condition exceptionnelle (ou exception) durant son ex ecution. Une exception est une situation qui emp eche lex ecution normale du programme (elle nest pas un bug ). Exemple : Un chier n ecessaire ` a lex ecution du programme nexiste pas. Division par z ero D ebordement dans un tableau etc.

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

192 / 379

Java

Cours 6

M ecanisme de gestion des exceptions


Java propose un m ecanisme de gestion des exceptions an de distinguer lex ecution normale du traitement des erreurs et faciliter la gestion des exceptions. En Java, une exception est une instance dune classe qui etend la classe Exception Pour lever (d eclencher) une exception, on utilise le mot-cl e throw :
i f ( p r o b l e m ) throw new M y E xc ep t i o n ( e r r e u r de t y p e 2 ) ;

Pour capturer une exception, on utilise la syntaxe try/catch :


try { // Probl` eme possible } catch ( MyException e ) { TraiterException (e ); }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

193 / 379

Java

Cours 6

D enir son propre type dexception


Il sut d etendre la classe Exception (ou une qui etend Exception) :
p u b l i c c l a s s MyException e x t e n d s E x c e p t i o n { i n t number ; p u b l i c MyException ( i n t number ) { t h i s . number = number ; } p u b l i c S t r i n g getMessage ( ) { r e t u r n E r r e u r numero +number ; } }

Convention de nommage : quelquechose Exception


Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 194 / 379

Java

Cours 6

La syntaxe try/catch
public s t a t i c void t e s t ( i n t i ) { System . o u t . p r i n t ( A ) ; try { System . o u t . p r i n t l n ( B ) ; i f ( i > 1 2 ) throw new MyException ( i ) ; System . o u t . p r i n t ( C ) ; } catch ( MyException e ) { System . o u t . p r i n t l n ( e ) ; } System . o u t . p r i n t l n ( D ) ; }

test(11) : A B C D
Bertrand Estellon (DIL Aix-Marseille)

test(13) : A B MyException: Erreur num ero 13 D


Programmation Orient ee Objet 29 mai 2012 195 / 379

Java

Cours 6

Pile dappels et exceptions


p u b l i c c l a s s Test { p u b l i c s t a t i c v o i d method1 ( i n t i ) t h r o w s M yE x ce pt i on { method2 ( i ) ; } p u b l i c s t a t i c v o i d method2 ( i n t i ) t h r o w s M yE x ce pt i on { i f ( i > 12) throw new M y E xc ep t i o n ( i ) ; } p u b l i c s t a t i c v o i d main ( S t r i n g a r g [ ] ) { t r y { method1 ( i ) ; } c a t c h ( M y E x c e pt i o n e ) { e . p r i n t S t a c k T r a c e ( ) ; } } }

Une m ethode doit indiquer toutes les exceptions quelle peut g en erer et quelle na pas trait ees avec un bloc try/catch
(Partiellement vrai => voir plus loin)
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 196 / 379

Java

Cours 6

Pile dappels et exceptions


p u b l i c c l a s s Test { p u b l i c s t a t i c v o i d method1 ( i n t method2 ( i ) ; } i ) throws MyException {

p u b l i c s t a t i c v o i d method2 ( i n t i ) t h r o w s M y E x c e p t i o n { i f ( i > 12) throw new M y E x c e p t i o n ( i ) ; } p u b l i c s t a t i c v o i d main ( S t r i n g a r g [ ] ) { t r y { method1 ( i ) ; } catch ( MyException e ) { e . p r i n t S t a c k T r a c e ( ) ; } } }

MyException: Erreur num ero 13 at Test.method2(Test.java:12) at Test.method1(Test.java:8) at Test.test(Test.java:17) at Test.main(Test.java:24)


Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 197 / 379

Java

Cours 6

La classe RuntimeException
Une m ethode doit indiquer toutes les exceptions quelle peut g en erer sauf si lexception etend la classe RuntimeException Bien evidemment, la classe RuntimeException etend Exception Quelques classes Java qui etendent RuntimeException : ArithmeticException ClassCastException IllegalArgumentException IndexOutOfBoundsException NegativeArraySizeException NullPointerException
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 198 / 379

Java

Cours 6

Capturer plusieurs types exceptions


public static int d i v i s e r ( Integer a , Integer b) { try { r e t u r n a /b ; } catch ( A r i t h m e t i c E x c e p t i o n e ) { e . printStackTrace (); r e t u r n I n t e g e r . MAX VALUE ; } catch ( N u l l P o i n t e r E x c e p t i o n e ) { e . printStackTrace (); return 0; } } }
diviser(12,0) : java.lang.ArithmeticException: / by zero at Test.diviser(Test.java:17) at Test.main(Test.java:28) 2147483647
Bertrand Estellon (DIL Aix-Marseille)

diviser(null,12) : java.lang.NullPointerException at Test.diviser(Test.java:17) at Test.main(Test.java:28) 0


29 mai 2012 199 / 379

Programmation Orient ee Objet

Java

Cours 6

Le mot-cl e nally
public s t a t i c void r e a d F i l e ( S t r i n g f i l e ) { try { F i l e R e a d e r f = new F i l e R e a d e r ( f i l e ) ; (le constructeur de FileReader peut d eclencher une FileNotFoundException) try { i n t ch = f . r e a d ( ) ; (peut d eclencher une IOException) w h i l e ( ch != 1) { System . o u t . p r i n t l n ( ch ) ; ch = f . r e a d ( ) ; (peut d eclencher une IOException) } } f i n a l l y { (` a faire dans tous les cas) f . close (); } } catch ( IOException e ) { e . p r i n t S t a c k T r a c e ( ) ; } }

FileNotFoundException etend IOException donc elle est captur ee


Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 200 / 379

Java

Cours 6

Le mot-cl e nally
public s t a t i c void r e a d F i l e ( S t r i n g f i l e ) { try { F i l e R e a d e r f = new F i l e R e a d e r ( f i l e ) ; (le constructeur de FileReader peut d eclencher une FileNotFoundException) try { i n t ch = f . r e a d ( ) ; (peut d eclencher une IOException) w h i l e ( ch != 1) { System . o u t . p r i n t l n ( ch ) ; ch = f . r e a d ( ) ; (peut d eclencher une IOException) } } f i n a l l y { (` a faire dans tous les cas) f . close (); } } catch ( FileNotFoundE xcept ion e ) { System . o u t . p r i n t l n ( F i c h i e r + f i l e + i n t r o u v a b l e ) ; } catch ( IOException e ) { e . p r i n t S t a c k T r a c e ( ) ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 201 / 379

Java

Cours 6

Exemple La pile
p u b l i c c l a s s P i l e <T> { private Object [ ] p i l e ; private int t a i l l e ; public Pile ( int capacity ) { p i l e = new O b j e c t [ c a p a c i t y ] ; }

t a i l l e = 0;

p u b l i c v o i d e m p i l e r (T o ) throws P i l e P l e i n e E x c e p t i o n { i f ( t a i l l e == p i l e . l e n g t h ) t h r o w new P i l e P l e i n e E x c e p t i o n ( ) ; p i l e [ t a i l l e ] = o ; t a i l l e ++; } p u b l i c T d e p i l e r ( ) throws P i l e V i d e E x c e p t i o n { i f ( t a i l l e == 0 ) t h r o w new P i l e V i d e E x c e p t i o n ( ) ; t a i l l e ; T e = (T) p i l e [ t a i l l e ] ; p i l e [ t a i l l e ]= n u l l ; r e t u r n (T) p i l e [ t a i l l e ] ; } }


Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 202 / 379

Java

Cours 6

Exemple La pile
D enition des exceptions :
p u b l i c c l a s s P i l e E x c e p t i o n extends Exception { p u b l i c P i l e E x c e p t i o n ( S t r i n g msg ) { s u p e r ( msg ) ; } }

p u b l i c c l a s s P i l e P l e i n e E x c e p t i o n extends P i l e E x c e p t i o n { p u b l i c P i l e P l e i n e E x c e p t i o n ( ) { super ( P i l e p l e i n e ) ; } }

p u b l i c c l a s s P i l e V i d e E x c e p t i o n extends P i l e E x c e p t i o n { p u b l i c P i l e V i d e E x c e p t i o n ( ) { super ( P i l e v i d e ) ; } }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

203 / 379

Java

Cours 6

Exemple La pile
Exemples dutilisation :
P i l e < I n t e g e r > p = new P i l e < I n t e g e r > ( 2 ) ; try { p . empiler (1); p . empiler (2); p . empiler (3); } catch ( P i l e E x c e p t i o n e ) { e . printStackTrace (); }
PilePleineException: Pile pleine at Pile.empiler(Pile.java:14) at Test.main(Test.java:58)

try { p . empiler (1); p. depiler (); p. depiler (); } catch ( P i l e E x c e p t i o n e ) { e . printStackTrace (); }
PileVideException: Pile vide at Pile.depiler(Pile.java:19) at Test.main(Test.java:67)

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

204 / 379

Java

Cours 6

La classe Throwable
En Java, toutes les instances des classes qui etendent Throwable peuvent etre jet ees et captur ees
Throwable

Error

Exception

RuntimeException

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

205 / 379

Java

Cours 6

La classe Throwable
La classe Throwable fournit les m ethodes suivantes :
Throwable Throwable() Throwable(message:String) Throwable(message:String, cause:Throwable) Throwable(cause:Throwable) fillInStackTrace():Throwable getCause():Throwable getLocalizedMessage():String getMessage():String getStackTrace():StackTraceElement[] initCause(cause:Throwable):Throwable printStackTrace():void printStackTrace(s:PrintStream):void printStackTrace(s:PrintWriter):void setStackTrace(stackTrace:StackTraceElement[]):void toString():String
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 206 / 379

Java

Cours 6

Quelques erreurs et exceptions standards


Error : indique un probl` eme s erieux
VirtualMachineError
InternalError OutOfMemoryError StackOverowError UnknownError

ThreadDeath

RuntimeException : exception qui na pas besoin d etre captur ee


ArithmeticException ClassCastException IllegalArgumentException IndexOutOfBoundsException NegativeArraySizeException NullPointerException

Exception :
IOException
FileNotFoundException SocketException
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 207 / 379

Java

Cours 6

R esum e

Structures de donn ees M ecanisme de gestion des exceptions La classe Exception D enir un type dexception Mot-cl e throw Utilisations de try, catch et nally Mot-cl e throws Les classes RuntimeException, Throwable et Error Les exceptions de Java

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

208 / 379

Java

Cours 7

UML

UML = Unied Modeling Language. UML est un langage de mod elisation graphique. UML est apparu dans le cadre de la conception orient ee objet . UML propose 13 types de diagrammes qui permettent la mod elisation dun projet durant tout son cycle de vie. Nous allons nous int eresser aux diagrammes de classes.

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

209 / 379

Java

Cours 7

Diagramme de classes

Sch ema utilis e pour repr esenter les classes et les interfaces. On repr esente egalement les int eractions entre les classes. Il est statique : on fait abstraction des aspects temporels. On peut ecrire notre programme ` a partir du diagramme de classes. Il permet de r e echir ` a la structure du programme. Il permet de d ecrire la structure du programme.

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

210 / 379

Java

Cours 7

Sch ema dune classe

Champ nom : type M ethode nom ( arguments ) : type Arguments argument ( , argument ) * Argument nom : type

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

211 / 379

Java

Cours 7

Classes et m ethodes abstraites

A droite, la m ethode method2 est abstraite. Donc, ` a droite, la classe est abstraite.

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

212 / 379

Java

Cours 7

Visibilit e

# +

: : : :

priv e (private ) prot eg e (protected ) publique (public ) non-publique (default )

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

213 / 379

Java

Cours 7

Extensions et impl ementations

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

214 / 379

Java

Cours 7

Impl ementation multiples

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

215 / 379

Java

Cours 7

D ependances

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

216 / 379

Java

Cours 7

Associations

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

217 / 379

Java

Cours 7

Navigation

Entreprise utilise des m ethodes de Fournisseur Fournisseur ne connait pas (et nutilise pas) Entreprise Sans ` eche, une association est navigable dans les deux sens
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 218 / 379

Java

Cours 7

Multiplicit e

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

219 / 379

Java

Cours 7

Multiplicit e

Notation 0..1 1 0..* (ou *) 1..* n 0..n 1..n

Signication Z ero ou un un uniquement Z ero ou plus Un ou plus Seulement n Z ero ` an Un ` an

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

220 / 379

Java

Cours 7

Agr egations

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

221 / 379

Java

Cours 7

Compositions

Les pi` eces composent la maison. Les pi` eces nexistent que si la maison existe.
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 222 / 379

Java

Cours 7

Nommage des relations

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

223 / 379

Java

Cours 7

Exemple de diagramme de classes


interface Formule + afficher() : String + evaluer() : double *

OperateurNAire Variable - name : String - value : double + afficher() : String + evaluer() : double + set(v : double) + f : Formule[] + OperateurNAire(f : Formule[]) + OperateurNAire(f1 : Formule, f2 : Formule) + afficher() : String + evaluer() : double # symbole() : char # evaluerBinaire(a : double, b : double) : double # evaluerVide() : double

Produit + Produit(f : Formule[]) + Produit(f1 : Formule, f2 : Formule) # symbole() : char # evaluerBinaire(a : double, b : double) : double # evaluerVide() : double

Somme + Somme(f : Formule[]) + Somme(f1 : Formule, f2 : Formule) # symbole() : char # evaluerBinaire(a : double, b : double) : double # evaluerVide() : double

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

224 / 379

Java

Cours 7

Exemple de diagramme de classes


JPanel

ShapePanel - shapes : ArrayList<Shape> + ShapePanel() + add(p : Shape) # paintComponent(g : Graphics)

* interface Shape + paint(g : Graphics) + getNumberOfPoints() : int + getPoint(i : int) : Point

AbstractShape - points : List<Point> + AbstractShape() # addPoint(p : Point) + getPoint(i : int) : Point + getNumberOfPoints() : int + paint(g : Graphics)

Decorator # decoratedShape : Shape + Decorator(decoratedShape : Shape) + paint(g : Graphics) + getNumberOfPoints() : int + getPoint(i : int) : Point # paintDecoration(g : Graphics)

Polygon - color : Color + Polygon(color : Color, points : Point[]) + paint(g : Graphics) - color : Color

Rectangle + Rectangle(p0 : Point, p1 : Point, color : Color) + paint(g : Graphics)

* Point

BorderDecorator - radius : int - color : Color + BorderDecorator(s : Shape, radius : int, color : Color) # paintDecoration(g : Graphics)

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

225 / 379

Java

Cours 7

La programmation orient ee objet (POO)

Les objectifs : Faciliter le d eveloppement et l evolution des applications ; Permettre le travail en equipe ; Augmenter la qualit e des logiciels (moins de bugs). Solutions propos ees : D ecoupler (s eparer) les parties des projets ; Limiter (et localiser) les modications lors des evolutions ; R eutiliser facilement du code.

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

226 / 379

Java

Cours 7

D eveloppement dune application


Les di erentes phases du d eveloppement dune application : D enition du cahier des charges Conception de larchitecture g en erale Conception d etaill ee Impl ementation Tests unitaires Int egration Qualication (v erication de la conformit e aux sp ecications) Mise en production Maintenance : correction des bugs + evolutions

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

227 / 379

Java

Cours 7

Les evolutions

Prise en compte dune evolution : Modication du cahier des charges Adaptation de larchitecture Impl ementation des nouvelles fonctionnalit es Tests unitaires Int egration Qualication (v erication de la conformit e aux sp ecications) Mise en production

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

228 / 379

Java

Cours 7

Programme bien con cu


Un programme est bien con cu sil permet de : Absorber les changements avec un minimum deort Impl ementer les nouvelles fonctionnalit es sans toucher aux anciennes Modier les fonctionnalit es existantes en modiant localement le code Objectifs : Limiter les modules impact es
Simplier les tests unitaires Rester conforme ` a la partie des sp ecications qui nont pas chang e Facilit e lint egration

Gagner du temps Remarque : Le d eveloppement dune application est une suite d evolutions

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

229 / 379

Java

Cours 7

Les cinq principes (pour cr eer du code) SOLID


Single Responsibility Principle (SRP) :
Une classe ne doit avoir quune seule responsabilit e

Open/Closed Principle (OCP) :


Programme ouvert pour lextension, ferm e` a la modication

Liskov Substitution Principle (LSP) :


Les sous-types doivent etre substituables par leurs types de base

Interface Segregation Principle (ISP) :


Eviter les interfaces qui contiennent beaucoup de m ethodes

Dependency Inversion Principle (DIP) :


Les modules dun programme doivent etre ind ependants Les modules doivent d ependre dabstractions

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

230 / 379

Java

Cours 7

Single Responsibility Principle (SRP)


Principe : Une classe ne doit avoir quune seule responsabilit e (Robert C. Martin). Signication et objectifs : Une responsabilit e est une raison de changer Une classe ne doit avoir quune seule raison de changer Pourquoi ? Si une classe a plusieurs responsabilit es, elles sont coupl ees Dans ce cas, la modication dune des responsabilit es n ecessite de :
tester ` a nouveau limpl ementation des autres responsabilit es modier potentiellement les autres responsabilit es d eployer ` a nouveau les autres responsabilit es

Donc, vous risquez de :


introduire des bugs rendre moins locales les modications
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 231 / 379

Java

Cours 7

Single Responsibility Principle (SRP)


Principe : Une classe ne doit avoir quune seule responsabilit e (Robert C. Martin). Signication et objectifs : Une responsabilit e est une raison de changer Une classe ne doit avoir quune seule raison de changer Avantages : Diminution de la complexit e du code Am elioration de la lisibilit e du code Meilleure organisation du code Modication locale lors des evolutions Augmentation de la abilit e Les classes ont plus de chance d etre r eutilisables
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 231 / 379

Java

Cours 7

Single Responsibility Principle (SRP)


GraphicalApplication GeometricApplication

Rectangle

Violation de SRP :

+ Rectangle() + draw() + getArea() : double

GraphicalInterface GraphicalApplication

GraphicalRectangle GeometryApplication ~ GraphicalRectangle() + draw()

S eparation des responsabilit es :


GeometricRectangle

GraphicalInterface ~ GeometricRectangle() + getArea() : double

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

232 / 379

Java

Cours 7

Open/Closed Principle (OCP)


Principe : Programme ouvert pour lextension, ferm e` a la modication Signication : Vous devez pouvoir ajouter une nouvelle fonctionnalit e: en ajoutant des classes (Ouvert pour lextension) sans modier le code existant (ferm e` a la modication) Avantages : Le code existant nest pas modi e augmentation de la abilit e Les classes ont plus de chance d etre r eutilisables Simplication de lajout de nouvelles fonctionnalit es

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

233 / 379

Java

Cours 7

Open/Closed Principle (OCP)


c l a s s R e c t a n g l e { p u b l i c P o i n t p1 , p2 ; } class C i r c l e { public Point c ; public int r a d i u s ; } class GraphicTools { s t a t i c void drawRectangle ( Rectangle r ) { . . . } s t a t i c void drawCircle ( C i r c l e c ) { . . . } s t a t i c v o i d d r a w Sh ap es ( O b j e c t [ ] s h a p e s ) { for ( Object o : shapes ) { i f (o instanceof Rectangle ) { Rectangle r = ( Rectangle )o ; drawRectangle ( r ) ; } else i f (o instanceof C i r c l e ) { Circle c = ( Circle )o ; drawCircle (c ); } } } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 234 / 379

Java

Cours 7

Open/Closed Principle (OCP)


Solution : Abstraction et interfaces !
i n t e r f a c e Shape { p u b l i c v o i d draw ( ) ; } c l a s s R e c t a n g l e implements Shape { p u b l i c P o i n t p1 , p2 ; v o i d draw ( ) { . . . } } c l a s s C i r c l e implements Shape { public Point c ; public int r a d i u s ; v o i d draw ( ) { . . . } } class GraphicTools { s t a t i c v o i d d r a w S h ap es ( Shape [ ] s h a p e s ) { f o r ( Shape s : s h a p e s ) s . draw ( ) ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 235 / 379

Java

Cours 7

Liskov Substitution Principle (LSP)


Principe : Les sous-types doivent etre substituables par leurs types de base Signication : Si une classe A etend une classe B (ou impl emente une interface B) alors un programme P ecrit pour manipuler des instances de type B doit avoir le m eme comportement sil manipule des instances de la classe A. Avantages : Diminution de la complexit e du code Am elioration de la lisibilit e du code Meilleure organisation du code Modication locale lors des evolutions Augmentation de la abilit e Les classes ont plus de chance d etre r eutilisables
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 236 / 379

Java

Cours 7

Liskov Substitution Principle (LSP)

Une classe qui permet de repr esenter un rectangle g eom etrique :


public class Rectangle { p r i v a t e double w ; p r i v a t e double h ; public public public public public } v o i d s e t W i d t h ( double w) { t h i s . w = w ; } v o i d s e t H e i g h t ( double h ) { t h i s . h = h ; } double g e t W i d t h ( ) { r e t u r n w ; } double g e t H e i g h t ( ) { r e t u r n h ; } double g e t A r e a ( ) { r e t u r n w h ; }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

237 / 379

Java

Cours 7

Liskov Substitution Principle (LSP)


Un carr e est un rectangle donc on devrait pouvoir ecrire :
p u b l i c c l a s s S q u a r e extends R e c t a n g l e { p u b l i c v o i d s e t W i d t h ( double w) { super . s e t W i d t h (w ) ; super . s e t H e i g h t (w ) ; } p u b l i c v o i d s e t H e i g h t ( double h ) { super . s e t W i d t h ( h ) ; super . s e t H e i g h t ( h ) ; } }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

238 / 379

Java

Cours 7

Liskov Substitution Principle (LSP)


Violation de LSP :
public void t e s t ( Rectangle r ) { r . setWidth ( 2 ) ; r . setHeight (3); i f ( r . getArea ()!=32) System . o u t . p r i n t l n ( b i z a r r e ! ) ; }

La mauvaise question : Un carr e est-il un rectangle ? La bonne question : Pour les utilisateurs, votre carr e a-t-il le m eme comportement que votre rectangle ? La r eponse : Dans ce cas, NON
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 239 / 379

Java

Cours 7

Liskov Substitution Principle (LSP)


Une solution :
public abstract class RectangularShape { p u b l i c a b s t r a c t d ouble g e t W i d t h ( ) ; p u b l i c a b s t r a c t d ouble g e t H e i g h t ( ) ; p u b l i c do u ble g e t A r e a ( ) { r e t u r n g e t W i d t h ( ) g e t H e i g h t ( ) ; } } p u b l i c c l a s s Rectangle extends RectangularShape { p r i v a t e d ou b le w ; p r i v a t e d ou b le h ; public public public public } v o i d s e t W i d t h ( double w) { t h i s . w = w ; } v o i d s e t H e i g h t ( double h ) { t h i s . h = h ; } do u ble g e t W i d t h ( ) { r e t u r n w ; } do u ble g e t H e i g h t ( ) { r e t u r n h ; }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

240 / 379

Java

Cours 7

Liskov Substitution Principle (LSP)


Suite de la solution :
c l a s s Square extends RectangularShape { p r i v a t e d ou b le s ; p u b l i c v o i d s e t S i d e L e n g t h ( double s ) { t h i s . s = s ; } p u b l i c do u ble g e t W i d t h ( ) { r e t u r n s ; } p u b l i c do u ble g e t H e i g h t ( ) { r e t u r n s ; } }

Utilisation :
public void t e s t R e c t a n g l e ( Rectangle r ) { r . setWidth ( 2 ) ; r . setHeight ( 3 ) ; i f ( r . g e t A r e a ( ) ! = 3 2 ) System . o u t . p r i n t l n ( j a m a i s ! ) ; } p u b l i c void t e s t S q u a r e ( Square s ) { s . setSideLength (2); i f ( s . g e t A r e a ( ) ! = 2 2 ) System . o u t . p r i n t l n ( j a m a i s ! ) ; }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 241 / 379

Java

Cours 8

Plan du cours

Diagrammes de classes UML Principes SOLID :


Single Responsibility Principle (SRP) Open/Closed Principle (OCP) Liskov Substitution Principle (LSP) Interface Segregation Principle (ISP) Dependency Inversion Principle (DIP)

Patrons de conception

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

242 / 379

Java

Cours 8

Les cinq principes (pour cr eer du code) SOLID


Single Responsibility Principle (SRP) :
Une classe ne doit avoir quune seule responsabilit e

Open/Closed Principle (OCP) :


Programme ouvert pour lextension, ferm e` a la modication

Liskov Substitution Principle (LSP) :


Les sous-types doivent etre substituables par leurs types de base

Interface Segregation Principle (ISP) :


Eviter les interfaces qui contiennent beaucoup de m ethodes

Dependency Inversion Principle (DIP) :


Les modules dun programme doivent etre ind ependants Les modules doivent d ependre dabstractions

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

243 / 379

Java

Cours 8

Interface Segregation Principle (ISP)


Principe : Eviter les interfaces qui contiennent beaucoup de m ethodes Signication et objectifs : D ecouper les interfaces en responsabilit es distinctes (SRP) Quand une interface grossit, se poser la question du r ole de linferface Eviter de devoir impl ementer des services qui nont pas ` a etre propos es par la classe qui impl emente linterface Limiter les modications lors de la modication de linterface Avantages : Le code existant est moins modi e augmentation de la abilit e Les classes ont plus de chance d etre r eutilisables Simplication de lajout de nouvelles fonctionnalit es
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 244 / 379

Java

Cours 8

Interface Segregation Principle (ISP)


Exemple de violation de ISP :
Ent reprise - employers : ArrayList <Employer> + + + + Ent reprise() employer(e : Employer) licencier(e : Employer) produire()

* int erf ace Employer

+ t ravailler() + manger() + dormir()

Homme

Femme

+ + + +

Homme() t ravailler() manger() dormir()

+ + + +

Femme() t ravailler() manger() dormir()

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

245 / 379

Java

Cours 8

Interface Segregation Principle (ISP)


p u b l i c i n t e r f a c e Employer { void t r a v a i l l e r ( ) ; v o i d manger ( ) ; void dormir ( ) ; }

p u b l i c c l a s s Femme implements E m p l o y e r { public void t r a v a i l l e r () { System . o u t . p r i n t l n ( Je s u i s une femme e t j e t r a v a i l l e ) ; } p u b l i c v o i d manger ( ) { System . o u t . p r i n t l n ( Je s u i s une femme e t j e mange ) ; } public void dormir () { System . o u t . p r i n t l n ( Je s u i s une femme e t j e d o r s ) ; } }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

246 / 379

Java

Cours 8

Interface Segregation Principle (ISP)


public class Entreprise { p r i v a t e f i n a l A r r a y L i s t <Employer > e m p l o y e r s ; public Entreprise () { e m p l o y e r s = new A r r a y L i s t <Employer > ( ) ; } p u b l i c void employer ( Employer e ) { e m p l o y e r s . add ( e ) ; } p u b l i c void l i c e n c i e r ( Employer e ) { e m p l o y e r s . remove ( e ) ; } public void p r o d u i r e () { f o r ( Employer e : employers ) e. travailler (); } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 247 / 379

Java

Cours 8

Interface Segregation Principle (ISP)


Un robot peut travailler :
Ent reprise - employers : ArrayList <Employer> + + + + Ent reprise() employer(e : Employer) licencier(e : Employer) produire()

* int erf ace Employer

+ t ravailler() + manger() + dormir()

Robot

Homme

Femme

+ + + +

Robot () t ravailler() manger() dormir()

+ + + +

Homme() t ravailler() manger() dormir()

+ + + +

Femme() t ravailler() manger() dormir()

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

248 / 379

Java

Cours 8

Interface Segregation Principle (ISP)


Probl` eme : un robot est un travailleur qui ne sait pas dormir et manger
p u b l i c c l a s s Robot implements E m p l o y e r { public void t r a v a i l l e r () { System . o u t . p r i n t l n ( j e t r a v a i l l e ) ; } p u b l i c v o i d manger ( ) { System . o u t . p r i n t l n ( j e ne s a i s p a s l e f a i r e ) ; } public void dormir () { System . o u t . p r i n t l n ( j e ne s a i s p a s l e f a i r e ) ; } }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

249 / 379

Java

Cours 8

Interface Segregation Principle (ISP)


Solution : d ecouper linterface Travailleur en deux
Ent reprise - employers : ArrayList <Employer> + + + + Ent reprise() employer(e : Employer) licencier(e : Employer) produire()

* int erf ace Employer int erf ace Humain

+ t ravailler()

+ manger() + dormir()

Femme Robot + + + + Femme() t ravailler() manger() dormir() + + + +

Homme

+ Robot () + t ravailler()

Homme() t ravailler() manger() dormir()

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

250 / 379

Java

Cours 8

Dependency Inversion Principle (DIP)


Principe : Les modules dun programme doivent etre ind ependants Les modules doivent d ependre dabstractions Signication et objectifs : D ecoupler les di erents modules de votre programme Les lier en utilisant des interfaces D ecrire correctement le comportement de chaque module Permet de remplacer un module par un autre module plus facilement Avantages : Les modules sont plus facilement r eutilisables Simplication de lajout de nouvelles fonctionnalit es Lint egration est rendue plus facile
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 251 / 379

Java

Cours 8

Dependency Inversion Principle (DIP)

ShapePanel - shapes : ArrayList <Shape> + ShapePanel() + addShape(s : Shape)

* int erf ace Shape

+ draw(g : Graphics)

Rect angle - p1 : Point - p2 : Point + Rect angle(p1 : Point , p2 : Point ) + draw(g : Graphics)

Circle ~ c : Point ~ radius : int + Circle(c : Point , radius : int ) + draw(g : Graphics)

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

252 / 379

Java

Cours 8

Dependency Inversion Principle (DIP)

ShapePanel - shapes : ArrayList <Shape> + ShapePanel() + addShape(s : Shape)

* int erf ace Shape FileLoader

+ draw(g : Graphics)

+ FileLoader()

inst ancie

inst ancie

Rect angle - p1 : Point - p2 : Point + Rect angle(p1 : Point , p2 : Point ) + draw(g : Graphics)

Circle ~ c : Point ~ radius : int + Circle(c : Point , radius : int ) + draw(g : Graphics)

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

253 / 379

Java

Cours 8

Dependency Inversion Principle (DIP)


public class FileLoader { p u b l i c void l o a d C i r c l e ( ShapePanel p , Scanner s ) { int x = s . nextInt (); int y = s . nextInt (); int r = s . nextInt (); p . addShape ( new C i r c l e ( new P o i n t ( x , y ) , r ) ) ; } p u b l i c void l o a d R e c t a n g l e ( ShapePanel p , Scanner s ) { int x = s . nextInt (); int y = s . nextInt (); i n t x2 = s . n e x t I n t ( ) ; i n t y2 = s . n e x t I n t ( ) ; p . addShape ( new R e c t a n g l e ( new P o i n t ( x , y ) , new P o i n t ( x2 , y2 ) ) ) ; } ...
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 254 / 379

Java

Cours 8

Dependency Inversion Principle (DIP)

p u b l i c v o i d l o a d F i l e ( S h a p e P a n e l p , S t r i n g name ) { S c a n n e r s = new S c a n n e r ( name ) ; while ( s . hasNext ( ) ) { switch ( s . n e x t I n t ( ) ) { case 0 : l oa dC i r cl e (p , s ) ; case 1 : loadRectangle (p , s ) ; } } s . nextInt (); } }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

255 / 379

Java

Cours 8

Dependency Inversion Principle (DIP)


ShapePanel - shapes : ArrayList <Shape> + ShapePanel() + addShape(s : Shape)

* int erf ace Shape

+ draw(g : Graphics)

Rect angle - p1 : Point - p2 : Point + Rect angle(p1 : Point , p2 : Point ) + draw(g : Graphics)

Circle ~ c : Point ~ radius : int + Circle(c : Point , radius : int ) + draw(g : Graphics)

NewCircle

+ NewCircle(c : Point , radius : int ) + draw(g : Graphics)

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

256 / 379

Java

Cours 8

Dependency Inversion Principle (DIP)


ShapePanel - shapes : ArrayList <Shape> + ShapePanel() + addShape(s : Shape)

* int erf ace Shape FileLoader

+ draw(g : Graphics)

+ FileLoader()

inst ancie

Circle ~ c : Point ~ radius : int + Circle(c : Point , radius : int ) + draw(g : Graphics) - p1 : Point - p2 : Point

Rect angle inst ancie

+ Rect angle(p1 : Point , p2 : Point ) + draw(g : Graphics)

NewCircle

+ NewCircle(c : Point , radius : int ) + draw(g : Graphics)

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

257 / 379

Java

Cours 8

Dependency Inversion Principle (DIP)


Violation de OCP car on viole DIP :
public class FileLoader { p u b l i c void l o a d C i r c l e ( ShapePanel p , Scanner s ) { int x = s . nextInt (); int y = s . nextInt (); int r = s . nextInt (); p . addShape ( new N e w C i r c l e ( new P o i n t ( x , y ) , r ) ) ; } p u b l i c void l o a d R e c t a n g l e ( ShapePanel p , Scanner s ) { int x = s . nextInt (); int y = s . nextInt (); i n t x2 = s . n e x t I n t ( ) ; i n t y2 = s . n e x t I n t ( ) ; p . addShape ( new R e c t a n g l e ( new P o i n t ( x , y ) , new P o i n t ( x2 , y2 ) ) ) ; } ...
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 258 / 379

Java

Cours 8

Dependency Inversion Principle (DIP)


FileLoader ShapePanel - shapes : ArrayList <Shape> + ShapePanel() + addShape(s : Shape) + + + + FileLoader() loadCircle(p : ShapePanel, s : Scanner) loadRect angle(p : ShapePanel, s : Scanner) loadFile(p : ShapePanel, name : St ring)

use * int erf ace Shape ShapeFact ory

+ draw(g : Graphics)

+ ShapeFact ory() + creat eCircle(p : Point , radius : int ) : Shape + creat eRect angle(p1 : Point , p2 : Point ) : Shape

inst ancie

Circle ~ c : Point ~ radius : int + Circle(c : Point , radius : int ) + draw(g : Graphics) - p1 : Point - p2 : Point

Rect angle inst ancie

+ Rect angle(p1 : Point , p2 : Point ) + draw(g : Graphics)

NewCircle

+ NewCircle(c : Point , radius : int ) + draw(g : Graphics)

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

259 / 379

Java

Cours 8

Dependency Inversion Principle (DIP)

public c l a s s ShapeFactory { p u b l i c Shape c r e a t e C i r c l e ( P o i n t p , i n t r a d i u s ) { r e t u r n new N e w C i r c l e ( p , r a d i u s ) ; } p u b l i c Shape c r e a t e R e c t a n g l e ( P o i n t p1 , P o i n t p2 ) { r e t u r n new R e c t a n g l e ( p1 , p2 ) ; } }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

260 / 379

Java

Cours 8

Dependency Inversion Principle (DIP)


public class FileLoader { p r i v a t e S h a p e F a c t o r y f a c t o r y = new S h a p e F a c t o r y ( ) ; p u b l i c void l o a d C i r c l e ( ShapePanel p , Scanner s ) { int x = s . nextInt (); int y = s . nextInt (); int r = s . nextInt (); p . addShape ( f a c t o r y . c r e a t e C i r c l e ( new P o i n t ( x , y ) , r ) ) ; } p u b l i c void l o a d R e c t a n g l e ( ShapePanel p , Scanner s ) { int x = s . nextInt (); int y = s . nextInt (); i n t x2 = s . n e x t I n t ( ) ; i n t y2 = s . n e x t I n t ( ) ; p . addShape ( f a c t o r y . c r e a t e R e c t a n g l e ( new P o i n t ( x , y ) , new P o i n t ( x2 , y2 ) ) ) ; } ...
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 261 / 379

Java

Cours 8

Dependency Inversion Principle (DIP)


Question : Comment faire cohabiter les deux fabriques suivantes ?
public class ShapeFactoryVersion1 { p u b l i c Shape c r e a t e C i r c l e ( P o i n t p , i n t r a d i u s ) { r e t u r n new C i r c l e ( p , r a d i u s ) ; } p u b l i c Shape c r e a t e R e c t a n g l e ( P o i n t p1 , P o i n t p2 ) { r e t u r n new R e c t a n g l e ( p1 , p2 ) ; } } public class ShapeFactoryVersion2 { p u b l i c Shape c r e a t e C i r c l e ( P o i n t p , i n t r a d i u s ) { r e t u r n new N e w C i r c l e ( p , r a d i u s ) ; } p u b l i c Shape c r e a t e R e c t a n g l e ( P o i n t p1 , P o i n t p2 ) { r e t u r n new R e c t a n g l e ( p1 , p2 ) ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 262 / 379

Java

Cours 8

Dependency Inversion Principle (DIP)

FileLoader - f act ory : Abst ract ShapeFact ory + + + + FileLoader(f act ory : Abst ract ShapeFact ory) loadCircle(p : ShapePanel, s : Scanner) loadRect angle(p : ShapePanel, s : Scanner) loadFile(p : ShapePanel, name : St ring)

use

int erf ace Abst ract ShapeFact ory

+ creat eCircle(p : Point , radius : int ) : Circle + creat eRect angle(p1 : Point , p2 : Point ) : Rect angle

ShapeFact oryVersion2

ShapeFact oryVersion1

+ ShapeFact oryVersion2() + creat eCircle(p : Point , radius : int ) : Circle + creat eRect angle(p1 : Point , p2 : Point ) : Rect angle

+ ShapeFact oryVersion1() + creat eCircle(p : Point , radius : int ) : Circle + creat eRect angle(p1 : Point , p2 : Point ) : Rect angle

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

263 / 379

Java

Cours 8

Dependency Inversion Principle (DIP)


interface AbstractShapeFactory + createCircle(p : Point, radius : int) : Circle + createRectangle(p1 : Point, p2 : Point) : Rectangle

ShapeFactoryVersion2 + ShapeFactoryVersion2() + createCircle(p : Point, radius : int) : Circle + createRectangle(p1 : Point, p2 : Point) : Rectangle

ShapeFactoryVersion1 + ShapeFactoryVersion1() + createCircle(p : Point, radius : int) : Circle + createRectangle(p1 : Point, p2 : Point) : Rectangle

instancie

instancie

instancie

Rectangle instancie - p1 : Point - p2 : Point + Rectangle(p1 : Point, p2 : Point) + draw(g : Graphics) - c : Point - radius : int

Circle

+ Circle(c : Point, radius : int) + draw(g : Graphics)

NewCircle + NewCircle(c : Point, radius : int) + draw(g : Graphics)

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

264 / 379

Java

Cours 8

Dependency Inversion Principle (DIP)


Diagramme de classes gobal :
FileLoader - factory : AbstractShapeFactory + + + + FileLoader(factory : AbstractShapeFactory) loadCircle(p : ShapePanel, s : Scanner) loadRectangle(p : ShapePanel, s : Scanner) loadFile(p : ShapePanel, name : String)

add shape

use

ShapePanel - shapes : ArrayList<Shape> + ShapePanel() + addShape(s : Shape)

interface AbstractShapeFactory + createCircle(p : Point, radius : int) : Circle + createRectangle(p1 : Point, p2 : Point) : Rectangle

* interface Shape + draw(g : Graphics) ShapeFactoryVersion1 + ShapeFactoryVersion1() + createCircle(p : Point, radius : int) : Circle + createRectangle(p1 : Point, p2 : Point) : Rectangle ShapeFactoryVersion2 + ShapeFactoryVersion2() + createCircle(p : Point, radius : int) : Circle + createRectangle(p1 : Point, p2 : Point) : Rectangle

instancie

instancie

instancie

Circle - c : Point - radius : int + Circle(c : Point, radius : int) + draw(g : Graphics) - p1 : Point - p2 : Point

Rectangle instancie

+ Rectangle(p1 : Point, p2 : Point) + draw(g : Graphics)

NewCircle + NewCircle(c : Point, radius : int) + draw(g : Graphics)

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

265 / 379

Java

Cours 8

Dependency Inversion Principle (DIP)


Application du DIP entre FileLoader et ShapePanel :
FileLoader - f act ory : Abst ract ShapeFact ory + + + + FileLoader(f act ory : Abst ract ShapeFact ory) loadCircle(p : ShapeCont ainer, s : Scanner) loadRect angle(p : ShapeCont ainer, s : Scanner) loadFile(p : ShapeCont ainer, name : St ring)

FileLoader - f act ory : Abst ract ShapeFact ory + + + + FileLoader(f act ory : Abst ract ShapeFact ory) loadCircle(p : ShapePanel, s : Scanner) loadRect angle(p : ShapePanel, s : Scanner) loadFile(p : ShapePanel, name : St ring)

add shape

int erf ace ShapeCont ainer

add shape + addShape(s : Shape) + removeShape(s : Shape)

ShapePanel - shapes : ArrayList <Shape> + ShapePanel() + addShape(s : Shape)

ShapePanel - shapes : ArrayList <Shape> + ShapePanel() + addShape(s : Shape) + removeShape(s : Shape)

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

266 / 379

Java

Cours 8

Dependency Inversion Principle (DIP)


public interface ShapeContainer { p u b l i c v o i d addShape ( Shape s ) ; p u b l i c v o i d removeShape ( Shape s ) ; } p u b l i c c l a s s ShapePanel extends JPanel implements S h a p e C o n t a i n e r { p r i v a t e f i n a l A r r a y L i s t <Shape > s h a p e s ; p u b l i c ShapePanel ( ) { s h a p e s = new A r r a y L i s t <Shape > ( ) ; } p u b l i c v o i d addShape ( Shape s ) { s h a p e s . add ( s ) ; } p u b l i c v o i d removeShape ( Shape s ) { s h a p e s . remove ( s ) ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 267 / 379

Java

Cours 8

Dependency Inversion Principle (DIP)


public class FileLoader { private f i n a l AbstractShapeFactory factory ; public FileLoader ( AbstractShapeFactory factory ) { this . factory = factory ; } public void l o a d C i r c l e ( ShapeContainer p , Scanner s ) { int x = s . nextInt () , y = s . nextInt (); int r = s . nextInt (); p . addShape ( f a c t o r y . c r e a t e C i r c l e ( new P o i n t ( x , y ) , r ) ) ; } public void loadRectangle ( ShapeContainer p , Scanner s ) { int x = s . nextInt () , y = s . nextInt (); i n t x2 = s . n e x t I n t ( ) , y2 = s . n e x t I n t ( ) ; p . addShape ( f a c t o r y . c r e a t e R e c t a n g l e ( new P o i n t ( x , y ) , new P o i n t ( x2 , y2 ) ) ) ; } ...
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 268 / 379

Java

Cours 8

Dependency Inversion Principle (DIP)


Diagramme de classes :
FileLoader

add shape

int erf ace ShapeCont ainer

use

ShapePanel

int erf ace Abst ract ShapeFact ory

* int erf ace Shape ShapeFact oryVersion1 ShapeFact oryVersion2

inst ancie inst ancie

inst ancie

Circle

Rect angle

inst ancie

NewCircle

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

269 / 379

Java

Cours 8

Patrons de conception (Design patterns)

Les patrons de conception d ecrivent des solutions standards pour r epondre aux probl` emes rencontr es lors de la conception orient ee objet Ils tendent ` a respecter les 5 principes SOLID Ils sont le plus souvent ind ependants du langage de programmation Ils ont et e formalis es dans le livre du Gang of Four ( Erich Gamma, Richard Helm, Ralph Johnson et John Vlissides 1995) Les patrons orent la possibilit e de capitaliser un savoir pr ecieux n e du savoir-faire dexperts (Buschmann 1996) Les anti-patrons (ou antipatterns) sont des erreurs courantes de conception.

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

270 / 379

Java

Cours 8

Patrons de conception GoF Cr eation

Fabrique abstraite (Abstract Factory) Monteur (Builder) Fabrique (Factory Method) Prototype (Prototype) Singleton (Singleton)

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

271 / 379

Java

Cours 8

Patrons de conception GoF Structure

Adaptateur (Adapter) Pont (Bridge) Objet composite (Composite) D ecorateur (Decorator) Fa cade (Facade) Poids-mouche ou poids-plume (Flyweight) Proxy (Proxy)

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

272 / 379

Java

Cours 8

Patrons de conception GoF Comportement


Cha ne de responsabilit e (Chain of responsibility) Commande (Command) Interpr eteur (Interpreter) It erateur (Iterator) M ediateur (Mediator) M emento (Memento) Observateur (Observer) Etat (State) Strat egie (Strategy) Patron de m ethode (Template Method) Visiteur (Visitor) Fonction de rappel (Callback)
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 273 / 379

Java

Cours 8

Fabrique abstraite
Utilisateur

utilise

utilise

interface ProduitAbstraitB

interface FabriqueAbstraite creerProduitA() : ProduitAbstraitA creerProduitB() : ProduitAbstraitB

utilise

FabriqueConcrete2 creerProduitA() : ProduitAbstraitA creerProduitB() : ProduitAbstraitB instancie instancie instancie

FabriqueConcrete1 creerProduitA() : ProduitAbstraitA creerProduitB() : ProduitAbstraitB instancie interface ProduitAbstraitA

ProduitB2

ProduitB1

ProduitA2

ProduitA1

Objectif : Isoler la cr eation des objets de leur utilisation


Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 274 / 379

Java

Cours 8

Adapteur
Utilisateur + Utilisateur()

utilise

interface InterfaceCible + methodA(a : String, b : int) + methodB(b : int, a : String)

methodA(a,b) method1(b,a) methodB(b,a) method2(b,a)

ClasseExistante + ClasseExistante() + method1(b : int, a : String) + method2(b : int, a : String)

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

275 / 379

Java

Cours 8

Adapteur
Utilisateur + Utilisateur()

public class Adapteur implements InterfaceCible {


utilise interface InterfaceCible + methodA(a : String, b : int) + methodB(b : int, a : String)

ClasseExistante classeExistante; public Adapteur() { classeExistante = new ClasseExistante(); } public void methodA(String a, int b) { classeExistante.method1(b, a); } public void methodB(int b, String a) { classeExistante.method2(b, a); } }

Adapteur ~ classeExistante : ClasseExistante + Adapteur() + methodA(a : String, b : int) + methodB(b : int, a : String) dlgue

ClasseExistante + ClasseExistante() + method1(b : int, a : String) + method2(b : int, a : String)

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

276 / 379

Java

Cours 8

Proxy
Client + Client()

utilise

interface IConteneur + set(v : int) + get() : int

public class Conteneur implements IConteneur { private int v; public void set(int v) { this.v = v; } public int get() { return v; }

Conteneur - v : int + Conteneur() + set(v : int) + get() : int

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

277 / 379

Java

Cours 8

Proxy
Client + Client()

utilise

public class ConteneurNonModifiable implements IConteneur { private Conteneur classeExistante; public ConteneurNonModifiable(Conteneur c) { classeExistante = c; } public void set(int v) { throw new UnsupportedOperationException(); } public int get() { return classeExistante.get(); } }
Programmation Orient ee Objet 29 mai 2012 278 / 379

interface IConteneur + set(v : int) + get() : int

ConteneurNonModifiable (Proxy) - classeExistante : Conteneur + ConteneurNonModifiable(c : Conteneur) + set(v : int) + get() : int dlgue

Conteneur - v : int + Conteneur() + set(v : int) + get() : int

Bertrand Estellon (DIL Aix-Marseille)

Java

Cours 8

Patron de m ethode
Exemple dutilisation du patron de m ethode :
OperateurNAire evaluer() : double evaluerBinaire(a : int, b : int) : int evaluerVide() : int

Produit evaluerBinaire(a : int, b : int) : int evaluerVide() : int

Somme evaluerBinaire(a : int, b : int) : int evaluerVide() : int

La classe OperateurNAire est abstraite ; La m ethode evaluer est une m ethode socle qui utilise evaluerBinaire et evaluerVide pour d enir son comportement ; Les m ethodes evaluerBinaire et evaluerVide sont abstraites dans OperateurNAire et d enies dans les classes qui etendent OperateurNAire ;
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 279 / 379

Java

Cours 8

Fonction de rappel (Callback)


C/C++ : typedef void (*Callback)(int); /* Pointeur sur fonction */ void callbackImpl1(int c) { printf("%d\n", c); } void callbackImpl2(int c) { printf("* %d *\n", c); } void function(int d, Callback callback) { /* ... */ callback(d); /* ... */ } int main(void) { function(2, callbackImpl1); function(4, callbackImpl2); }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 280 / 379

Java

Cours 8

Fonction de rappel (Callback)


Java :
public interface Callback { void method(int c); } public class CallbackImpl1 implements Callback { public void method(int c) { System.out.println(c); }

public class CallbackImpl2 implements Callback { public void method(int c) { System.out.println("* "+c+" *"); } public class MaClasse { public static void function(int d, Callback callback) { /* ... */ callback.method(d); /* ... */ } public static void main(String[] args) { Callback c1 = new CallbackImpl1(); function(2, c1); Callback c2 = new CallbackImpl2(); function(4, c2); } }
Programmation Orient ee Objet

Bertrand Estellon (DIL Aix-Marseille)

29 mai 2012

281 / 379

Java

Cours 8

Fonction de rappel (Callback)


C# :
using System; public delegate void Callback(int c); class MaClasse {

public static void callbackImpl1(int c) {Console.WriteLine("{0}",c);} public static void callbackImpl2(int c) {Console.WriteLine("* {0} *",c);} public static void function(int d, Callback callback) { /* ... */ callback(d); /* ... */ } static void Main(string[] args) { Callback c1 = new Callback(callbackImpl1); function(2,c1); Callback c2 = new Callback(callbackImpl2); function(4,c2); } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 282 / 379

Java

Cours 9

Les ux dentr ee-sortie


Les ux (stream) permettent denvoyer et de recevoir des donn ees Les noms des classes qui g` erent les ux se terminent par : Flux dentr ee Flux de sortie Flux doctets InputStream OutputStream Flux de caract` eres Reader Writer

Les classes qui g` erent les ux sont dans le package java.io Certaines classes permettent de lire ou d ecrire dans ou vers di erents supports (chier, cha ne de caract` eres, tubes, socket, etc.) Dautres permettent de faire des traitements sur les donn ees (ltres) InputStream, OutputStream, Reader, Writer = classes abstraites
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 283 / 379

Java

Cours 9

Les ux dentr ee (octets)


Flux doctets dentr ee ( etendant InputStream) : ByteArrayInputStream : Lecture dans un tableau doctets FileInputStream : Lecture dans un chier ObjectInputStream : Lecture dobjets dans un InputStream PipedInputStream : Lecture dans un tube SequenceInputStream : Union de plusieurs ux doctets AudioInputStream : Lecture dans un ux audio

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

284 / 379

Java

Cours 9

Les ux dentr ee (octets)


Flux doctets dentr ee ( etendant InputStream) : FilterInputStream : Ajoute un traitement sur le ux dentr ee
BueredInputStream : Ajoute un tapon CheckedInputStream : Calcule un checksum sur lentr ee CipherInputStream : Chire ou d echire le ux DataInputStream : Permet de lire des donn ees primitives Java LineNumberInputStream : Permet de conna tre la ligne courante InaterInputStream : Permet de d ecompresser un ux
GZIPInputStream : Format GZIP ZipInputStream : Format ZIP

...
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 285 / 379

Java

Cours 9

Les ux dentr ee (octets)

Exemple :
byte [ ] b y t e s = { 1 0 , 1 1 , 1 2 } ; I n p u t S t r e a m i s = new B y t e A r r a y I n p u t S t r e a m ( b y t e s ) ; while ( i s . a v a i l a b l e ( ) > 0) System . o u t . p r i n t l n ( i s . r e a d ( ) ) ;

Sortie :
10 11 12

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

286 / 379

Java

Cours 9

Les ux dentr ee (octets)


Les m ethodes de la classe InputStream : int available() : retourne nombre doctets restants void close() : ferme le ux void mark(int readlimit) : marque la position courante boolean markSupported() : est-ce mark et reset sont support es ? abstract int read() : lit un octet int read(byte[] b) : lit une sequence doctets int read(byte[] b, int o, int len) : lit une sequence doctets void reset() : retourne ` a la marque pr ec edente long skip(long n) : saute des octets

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

287 / 379

Java

Cours 9

Les ux dentr ee (octets)


Cr eation dun chier : $ echo "abc" > abc.txt Exemple de lecture dans un chier :
I n p u t S t r e a m i s = new F i l e I n p u t S t r e a m ( abc . t x t ) ; w h i l e ( i s . a v a i l a b l e () > 0) { System . o u t . p r i n t l n ( i s . r e a d ( ) ) ; } is . close ();

Sortie : 97 98 99 10
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 288 / 379

Java

Cours 9

Les ux dentr ee (octets)


Construction dun chier Zip : $ echo "abc" > abc.txt $ echo "truc" > truc.txt $ zip archive.zip abc.txt truc.txt Exemple de lecture dans un chier Zip :
I n p u t S t r e a m i s = new F i l e I n p u t S t r e a m ( a r c h i v e . z i p ) ; i s = new B u f f e r e d I n p u t S t r e a m ( i s ) ; Z i p I n p u t S t r e a m z i p = new Z i p I n p u t S t r e a m ( i s ) ; ZipEntry entry = zip . getNextEntry ( ) ; w h i l e ( e n t r y != n u l l ) { System . o u t . p r i n t l n ( Contenu de + e n t r y . getName ()+ : ) ; f o r ( i n t c = z i p . r e a d ( ) ; c != 1; c = z i p . r e a d ( ) ) System . o u t . p r i n t ( c+ ) ; zip . closeEntry (); entry = zip . getNextEntry ( ) ; } zip . close ();
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 289 / 379

Java

Cours 9

Les ux dentr ee (octets)


Construction dun chier Zip : $ echo "abc" > abc.txt $ echo "truc" > truc.txt $ zip archive.zip abc.txt truc.txt Sortie : Contenu de abc.txt : 97 98 99 10 Contenu de truc.txt : 116 114 117 99 10

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

290 / 379

Java

Cours 9

Les ux dentr ee (caract` eres)


Flux de caract` eres dentr ee ( etendant Reader) : CharArrayReader : Lecture dans un tableau de caract` eres BueredReader : Lecture avec un tapon
LineNumberReader : Permet de conna tre le num ero de ligne

InputStreamReader : Lecture dans un ux doctets


FileReader : Lecture dans un chier

PipedReader : Lecture dans un tube StringReader : Lecture dans une cha ne de caract` eres FilterReader : Ajoute un traitement sur le ux dentr ee
PushbackReader : Permet de remettre des caract` eres dans le ux
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 291 / 379

Java

Cours 9

Les ux dentr ee (caract` eres)

Exemple :
Reader r = new S t r i n g R e a d e r ( t o t o ) ;

int c ; w h i l e ( ( c = r . r e a d ())!= 1) System . o u t . p r i n t l n ( ( c h a r ) c ) ;

Sortie :
t o t o

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

292 / 379

Java

Cours 9

Les ux dentr ee (octets)


Les m ethodes de la classe Reader : void close() : ferme le ux void mark(int readlimit) : marque la position courante boolean markSupported() : est-ce mark et reset sont support es ? abstract int read() : lit un caract` ere int read(char[] b) : lit une s equence de caract` eres int read(char[] b, int o, int len) : lit une s equence de caract` eres int ready() : est-ce que le ux est pr et ` a etre lu ? void reset() : retourne ` a la marque pr ec edente long skip(long n) : saute des caract` eres

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

293 / 379

Java

Cours 9

Les ux dentr ee (caract` eres)

Pour lire un chier ligne ` a ligne, il faut utiliser un BueredReader :


R e a d e r r e a d e r = new S t r i n g R e a d e r ( L1 \ nL2 \ nL3 ) ; B u f f e r e d R e a d e r b u f f e r e d R e a d e r = new B u f f e r e d R e a d e r ( r e a d e r ) ; String ligne ; while (( l i g n e = bufferedReader . readLine ())!= n u l l ) System . o u t . p r i n t l n ( l i g n e ) ;

Sortie :
L1 L2 L3

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

294 / 379

Java

Cours 9

Les ux dentr ee (caract` eres)


Autre exemple :
R e a d e r r e a d e r = new S t r i n g R e a d e r ( L1 \ nL2 \ nL3 ) ; L i n e Number Re a de r l i n e N u m b e r R e a d e r = new LineNumber Reader ( r e a d e r ) ; String ligne ; while (( l i g n e = lineNumberReader . readLine ())!= n u l l ) { System . o u t . p r i n t l n ( l i n e N u m b e r R e a d e r . g e t L i n e N u m b e r ()+ : ) ; System . o u t . p r i n t l n ( l i g n e ) ; }

Sortie :
1 : L1 2 : L2 3 : L3

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

295 / 379

Java

Cours 9

Les ux de sortie (octets)

Flux doctets de sortie ( etendant OutputStream) : ByteArrayOutputStream : Ecriture dans un tableau doctets FileOutputStream : Ecriture dans un chier ObjectOutputStream : Ecriture dobjets dans un OutputStream PipedOutputStream : Ecriture dans un tube

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

296 / 379

Java

Cours 9

Les ux de sortie (octets)


Flux doctets de sortie ( etendant OutputStream) : FilterOutputStream : Ajoute un traitement sur le ux de sortie
BueredOutputStream : Ajoute un tapon CheckedOutputStream : Calcule un checksum sur la sortie CipherOutputStream : Chire ou d echire le ux DataOutputStream : Permet d ecrire des donn ees primitives Java PrintStream : Ajoute des fonctions de formatage DeaterOutputStream : Permet de compresser un ux
GZIPOutputStream : Format GZIP ZipOutputStream : Format ZIP

...
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 297 / 379

Java

Cours 9

Les ux de sortie (octets)


Exemple :
B y t e A r r a y O u t p u t S t r e a m o u t p u t = new B y t e A r r a y O u t p u t S t r e a m ( ) ; output . w r i t e ( 9 7 ) ; output . w r i t e ( 9 8 ) ; output . w r i t e ( 9 9 ) ; byte [ ] b y t e s = o u t p u t . t o B y t e A r r a y ( ) ; f o r ( byte b : b y t e s ) System . o u t . p r i n t l n ( b ) ; System . o u t . p r i n t l n ( o u t p u t ) ;

Sortie :
97 98 99 abc
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 298 / 379

Java

Cours 9

Les ux de sortie (octets)

Les m ethodes de la classe OutputStream : void close() : ferme le ux int write(byte[] b) : ecrit une sequence doctets int write(byte[] b, int o, int len) : ecrit une sequence doctets abstract void write(int b) : ecrit un octet sur le ux void ush() : force les buers ` a etre ecrit

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

299 / 379

Java

Cours 9

Les ux de sortie (octets)


Copie de deux chiers :
I n p u t S t r e a m i n p u t = new B u f f e r e d I n p u t S t r e a m ( new F i l e I n p u t S t r e a m ( o r i g i n a l . p d f ) ); OutputStream o u t p u t = new B u f f e r e d O u t p u t S t r e a m ( new F i l e O u t p u t S t r e a m ( c o p i e . p d f ) ); byte [ ] b = new byte [ 2 0 0 ] ; int n = input . read (b ) ; w h i l e ( n!= 1) { output . w r i t e (b , 0 , n ) ; n = input . read (b ) ; } input . close ( ) ; output . c l o s e ( ) ;
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 300 / 379

Java

Cours 9

Les ux de sortie (caract` eres)


Flux de caract` eres de sortie ( etendant Writer) : CharArrayWriter : Ecriture dans un tableau de caract` eres BueredWriter : Ecriture avec un tapon OutputStreamWriter : Ecriture dans un ux doctets
FileWriter : Ecriture dans un chier

PipedWriter : Ecriture dans un tube StringWriter : Ecriture dans une cha ne de caract` eres PrintWriter : Ecriture avec des m ethodes de formatage FilterWriter : Ajoute un traitement sur le ux de sortie
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 301 / 379

Java

Cours 9

Les ux de sortie (caract` eres)


Num erotation des lignes dun chier texte :
L i n e Number Re a de r i n p u t = new LineNumber Reader ( new F i l e R e a d e r ( t . t x t ) ); W r i t e r o u t p u t = new B u f f e r e d W r i t e r ( new F i l e W r i t e r ( t 2 . t x t ) ); String s = input . readLine ( ) ; w h i l e ( s != n u l l ) { o u t p u t . w r i t e ( i n p u t . g e t L i n e N u m b e r ()+ : ) ; o u t p u t . w r i t e ( s+\ n ) ; s = input . readLine ( ) ; } input . close ( ) ; output . c l o s e ( ) ;
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 302 / 379

Java

Cours 9

Les ux de sortie (caract` eres)


Ecriture format ee dans un chier :
P r i n t W r i t e r o u t p u t = new P r i n t W r i t e r ( t e x t e . t x t ) ; o u t p u t . p r i n t l n ( b o n j o u r ) ; o u t p u t . p r i n t f ( %d %d %d \ n , 1 2 , 1 4 , 1 5 ) ; o u t p u t . p r i n t f ( %s %.2 f %04d \ n , aaaa , 1 2 . 4 4 5 5 7 , 4 5 ) ; output . c l o s e ( ) ;

Contenu du chier apr` es lex ecution : bonjour 12 -- 14 -- 15 aaaa 12,45 0045

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

303 / 379

Java

Cours 9

System.{out,in,err}
Dans la classe System : public public public public Exemple :
System . o u t . p r i n t l n ( e c r i t u r e s u r l a s o r t i e s t a n d a r d ) ; System . e r r . p r i n t l n ( e c r i t u r e s u r l a s o r t i e d e r r e u r ) ; B u f f e r e d R e a d e r i n p u t = new B u f f e r e d R e a d e r ( new I n p u t S t r e a m R e a d e r ( System . i n ) ) ; String s = input . readLine ( ) ; w h i l e ( s != n u l l ) { System . o u t . p r i n t l n ( s ) ; s = input . readLine ( ) ; }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 304 / 379

static static static static

nal InputStream in : entr ee standard nal PrintStream out : sortie standard nal PrintStream err : sortie derreur Console console() : retourne la console

Java

Cours 9

System.console()
Dans la classe Console : void ush() : vide le buer Console format(String fmt, Object... args) : ecriture format ee Console printf(String format, Object... args) : ecriture format ee Reader reader() : retourne le Reader de la console String readLine() : lit une ligne String readLine(String fmt, Object... args) : idem avec format char[] readPassword() : lit un mot de passe char[] readPassword(String fmt, Object... args) : idem avec format PrintWriter writer() : retourne le Writer de la console Attention : System.console() retourne une r ef erence null si le syst` eme ne supporte pas cette fonctionnalit e
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 305 / 379

Java

Cours 9

Les exceptions et les erreurs


Quelques exceptions li ees aux entr ees-sorties : IOError IOException
EOFException FileNotFoundException ZipException CharacterCodingException
MalformedInputException UnmappableCharacterException

...

IllegalFormatException Exemple :
try { F i l e R e a d e r r e a d e r = new F i l e R e a d e r ( t r u c . t x t ) ; } c a t c h ( F i l e N o t F o u n d E x c e p t i o n ex ) { System . o u t . p r i n t l n ( t r u c . t x t n e x i s t e p a s ! ) ; }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 306 / 379

Java

Cours 9

Astuce : la classe Scanner


Exemples dutilisation de la classe Scanner :
S c a n n e r s c = new S c a n n e r ( System . i n ) ; int i = sc . nextInt ( ) ; S t r i n g i n p u t = 1 abc 2 abc t r u c abc machin abc ; S c a n n e r s = new S c a n n e r ( i n p u t ) . u s e D e l i m i t e r ( \\ s abc \\ s ) ; System . o u t . p r i n t l n ( s . n e x t I n t ( ) ) ; System . o u t . p r i n t l n ( s . n e x t I n t ( ) ) ; System . o u t . p r i n t l n ( s . n e x t ( ) ) ; System . o u t . p r i n t l n ( s . n e x t ( ) ) ; s . close (); S t r i n g i n p u t = 1 abc 2 abc t r u c abc machin abc ; S c a n n e r s = new S c a n n e r ( i n p u t ) ; s . f i n d I n L i n e ( ( \ \ d+) abc ( \ \ d+) abc ( \ \ w+) abc ( \ \ w+) ) ; M a t c h R e s u l t r e s u l t = s . match ( ) ; f o r ( i n t i =1; i <=r e s u l t . g r o u p C o u n t ( ) ; i ++) System . o u t . p r i n t l n ( r e s u l t . g r o u p ( i ) ) ; s . close ();
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 307 / 379

Java

Cours 9

Java et le multit ache

Un programme peut lancer plusieurs threads Les threads lanc es par un programme s executent en parall` ele Si lordinateur na pas assez de processeur pour ex ecuter tous les threads en parall` ele, le syst` eme dexploitation va simuler le multit ache en changeant r eguli` erement le thread en cours dex ecution Tous les threads partagent le m eme espace m emoire En Java, linterface Runnable et la classe Thread permettent de cr eer des threads

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

308 / 379

Java

Cours 9

Linterface Runnable
Linterface Runnable contient la m ethode void run() p u b l i c c l a s s Compteur implements R u n n a b l e { public void run ( ) { int cpt = 0; while ( cpt < 100) { System . o u t . p r i n t ( c p t+ ) ; c p t ++; } } }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

309 / 379

Java

Cours 9

La classe Thread
Chaque instance de cette classe correspond ` a un thread Elle impl emente linterface Runnable Quelques m ethodes non-statiques de la classe Thread : Thread() : constructeur par d efaut Thread(Runnable target) : constructeur avec un Runnable void start() : d emarre le thread void join() : attend que le thread meure void interrupt() : interrompt le thread boolean isAlive() : est-ce que le thread est en vie ? boolean isInterrupted() : est-ce que le thread est interrompu ? boolean isDaemon() : est-ce que le thread est un d emon ?
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 310 / 379

Java

Cours 9

Lancement dun thread


Premi` ere m ethode :
p u b l i c c l a s s Compteur implements R u n n a b l e { p u b l i c void run ( ) { int cpt = 0; w h i l e ( c p t < 1 0 ) { System . o u t . p r i n t ( c p t+ ) ; c p t ++; } } } p u b l i c c l a s s Main { p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) { Thread t h 1 = new Thread ( new Compteur ( ) ) ; th1 . s t a r t ( ) ; Thread t h 2 = new Thread ( new Compteur ( ) ) ; th2 . s t a r t ( ) ; } }

Sortie : 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 311 / 379

Java

Cours 9

Lancement dun thread


Deuxi` eme m ethode :
p u b l i c c l a s s Compteur e x t e n d s Thread { p u b l i c void run ( ) { int cpt = 0; w h i l e ( c p t < 1 0 ) { System . o u t . p r i n t ( c p t+ ) ; c p t ++; } } } p u b l i c c l a s s Main { p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) { Thread t h 1 = new Compteur ( ) ; th1 . s t a r t ( ) ; Thread t h 2 = new Compteur ( ) ; th2 . s t a r t ( ) ; } }

Sortie : 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 312 / 379

Java

Cours 9

La classe Thread

Les m ethodes statiques agissent sur le thread en cours dex ecution

Quelques m ethodes statiques de la classe Thread : Thread currentThread() : retourne le thread courant boolean interrupted() : est-ce que le thread courant est interrompu ? void sleep(long millis) : endort le thread courant void yield() : interrompt le thread courant int activeCount() : nombre de threads actifs

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

313 / 379

Java

Cours 9

L etat dinterruption
Interrompre un thread signie vouloir quil arr ete son ex ecution Un thread peut etre interrompu avec la m ethode interrupt() Si le thread dort, il faut le r eveiller pour quil puisse sinterrompre Solution : L etat dinterruption et lexception InterruptedException La m ethode interrupted() permet de consulter l etat dinterruption Compteur qui sarr ete quand le thread est interrompu :
p u b l i c c l a s s Compteur e x t e n d s Thread { p u b l i c void run ( ) { int cpt = 0; w h i l e ( ! i n t e r r u p t e d ( ) ) c p t ++; System . o u t . p r i n t l n ( c p t ) ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 314 / 379

Java

Cours 9

L etat dinterruption
Utilisation du compteur :
p u b l i c c l a s s Main { p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) { Thread t h 1 = new Compteur ( ) ; th1 . s t a r t ( ) ; . . . ; th1 . i n t e r r u p t ( ) ; } }

Compteur qui compte moins vite :


p u b l i c c l a s s Compteur e x t e n d s Thread { p u b l i c void run ( ) { int cpt = 0; while ( ! i n t e r r u p t e d ()) { c p t ++; Thread . s l e e p ( 1 0 0 ) ; // Probl` eme : interruption pendant que je dors ! } System . o u t . p r i n t l n ( c p t ) ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 315 / 379

Java

Cours 9

L etat dinterruption
Utilisation du compteur :
p u b l i c c l a s s Main { p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) { Thread t h 1 = new Compteur ( ) ; th1 . s t a r t ( ) ; . . . ; th1 . i n t e r r u p t ( ) ; } }

Compteur qui compte moins vite :


p u b l i c c l a s s Compteur e x t e n d s Thread { p u b l i c void run ( ) { int cpt = 0; while ( ! i n t e r r u p t e d ()) { c p t ++; t r y { Thread . s l e e p ( 1 0 0 ) ; } catch ( InterruptedException e ) { break ; } } System . o u t . p r i n t l n ( c p t ) ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 316 / 379

Java

Cours 9

L etat dinterruption
Thread qui interrompt un autre thread apr` es un certain temps :
p u b l i c c l a s s S t o p p e r e x t e n d s Thread { Thread t h r e a d ; int timeLimit ; p u b l i c S t o p p e r ( Thread t h r e a d , i n t t i m e L i m i t ) { this . thread = thread ; this . timeLimit = timeLimit ; } void run ( ) { try { sleep ( timeLimit ); } c a t c h ( I n t e r r u p t e d E x c e p t i o n ex ) { return ; } thread . i n t e r r u p t ( ) ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 317 / 379

Java

Cours 9

L etat dinterruption
Exemple dutilisation des classes pr ec edentes :
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) { Thread t h 1 = new Compteur ( ) ; th1 . s t a r t ( ) ; Thread t h 2 = new S t o p p e r ( th1 , 3 5 0 ) ; th2 . s t a r t ( ) ; }

Ex ecution :
4 1 Compteur 0 1 Stopper 0
Programmation Orient ee Objet

2 100

3 200

4 300
temps interrupt() temps

350

Bertrand Estellon (DIL Aix-Marseille)

29 mai 2012

318 / 379

Java

Cours 9

Probl` eme de synchronisation


Une pile dentiers avec une temporisation lors des empilements :
public class PileLente { p r i v a t e i n t [ ] tab ; p r i v a t e i n t s i z e ; public PileLente () { t a b = new i n t [ 1 0 0 0 ] ; s i z e = 0 ; } v o i d push ( i n t p ) throws I n t e r r u p t e d E x c e p t i o n { i n t s = s i z e ; tab [ s ] = p ; Thread . s l e e p ( 1 0 0 ) ; size = s + 1; } i n t pop ( ) { s i z e ; r e t u r n t a b [ s i z e ] ; } int s i z e () { return s i z e ; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 319 / 379

Java

Cours 9

Synchronisation
Un thread qui empile 10 entiers :
p u b l i c c l a s s E m p i l e u r e x t e n d s Thread { private PileLente p i l e ; public Empileur ( PileLente p i l e ) { this . pile = pile ; } p u b l i c void run ( ) { f o r ( i n t i = 0 ; i < 1 0 ; i ++) try { p i l e . push ( i ) ; } c a t c h ( I n t e r r u p t e d E x c e p t i o n ex ) { return ; } } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 320 / 379

Java

Cours 9

Synchronisation
Ex ecution en parall` ele de deux empileurs sur une m eme pile :
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) throws I n t e r r u p t e d E x c e p t i o n { P i l e L e n t e p i l e = new P i l e L e n t e ( ) ; Thread t h 1 = new E m p i l e u r ( p i l e ) ; Thread t h 2 = new E m p i l e u r ( p i l e ) ; th1 . s t a r t ( ) ; th2 . s t a r t ( ) ; t h 1 . j o i n ( ) ; // On attend la n du thread 1 t h 2 . j o i n ( ) ; // On attend la n du thread 2 w h i l e ( p i l e . s i z e () > 0) { System . o u t . p r i n t ( p i l e . pop ()+ ) ; }

Sortie : 9 8 7 6 5 4 3 2 1 0 Question : O` u sont pass es les 10 el ements manquants ?


Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 321 / 379

Java

Cours 9

Synchronisation
Ex ecution (en parall` ele) de la m ethode push dans deux threads : Thread 1 int s = size ; (s = x ) tab[s] = p ; sleep(100) ; size = s + 1 ; (size = x + 1) Thread 2

int s = size ; (s = x ) tab[s] = p ; sleep(100) ; size = s + 1 ; (size = x + 1)

Probl` eme : Deux entiers ont et e empil es et la pile et la taille de la pile est pass ee de x ` a x +1

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

322 / 379

Java

Cours 9

Le mot-cl e Synchronized
Interdire que deux invocations sur une m eme instance sentrem elent :
public class PileLente { ... s y n c h r o n i z e d v o i d push ( i n t p ) throws I n t e r r u p t e d E x c e p t i o n { i n t s = s i z e ; tab [ s ] = p ; Thread . s l e e p ( 1 0 0 ) ; size = s + 1; } s y n c h r o n i z e d i n t pop ( ) { s i z e ; r e t u r n t a b [ s i z e ] ; } ... }

Signication : Si un thread T invoque la m ethode push alors quune autre m ethode synchronis ee est en cours dex ecution dans un autre thread alors le thread T est suspendu et doit attendre que la m ethode push soit disponible (cest-` a-dire, quaucun thread ne soit en train dex ecuter une m ethode synchronis ee sur linstance)
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 323 / 379

Java

Cours 9

Obtenir des structures synchronis ees en Java


Transformation dune structure de donn ees en sa version synchronis ee :
C o l l e c t i o n < S t r i n g > c o l l e c t i o n = new A r r a y L i s t < S t r i n g > ( ) ; collection = Collections . synchronizedCollection ( collection ); L i s t < S t r i n g > l i s t = new A r r a y L i s t < S t r i n g > ( ) ; l i s t = Collections . synchronizedList ( l i s t ); Set < S t r i n g > s e t = new HashSet < S t r i n g > ( ) ; set = Collections . synchronizedSet ( set ); Map< S t r i n g , I n t e g e r > map = new HashMap< S t r i n g , I n t e g e r > ( ) ; map = C o l l e c t i o n s . s y n c h r o n i z e d M a p ( map ) ;

Question : Comment obtenir la m eme fonctionnalit e sur une structure de donn ees que vous avez ecrite ?
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 324 / 379

Java

Cours 9

Swing et les threads


Chaque ev` enement est g er e dans un thread s epar e Si une exception est jet ee lors de son traitement, seul le thread est tu e Cela permet de rendre les applications graphiques plus robustes La bonne fa con de d ebuter une application Swing :
p u b l i c c l a s s Main { public void creerEtMontrer () { . . . . } p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) { S w i n g U t i l i t i e s . i n v o k e L a t e r ( new R u n n a b l e ( ) { p u b l i c void run ( ) { creerEtMontrer ( ) ; } }); } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 325 / 379

Java

Cours 10

JavaDoc
Outil pour g en erer automatiquement une documentation du code Il g en` ere une documentation au format HTML Cette documentation est lisible dans Eclipse ou NetBeans Le document contient :
Une description des membres (publics et prot eg es) des classes Des liens permettant de naviguer entre les classes Des informations sur lh eritage

La documentation est g en er ee ` a partir des commentaires Les commentaires doivent respecter un certain format

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

326 / 379

Java

Cours 10

Exemple de JavaDoc

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

327 / 379

Java

Cours 10

Exemple de JavaDoc

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

328 / 379

Java

Cours 10

Exemple de JavaDoc

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

329 / 379

Java

Cours 10

Exemple de commentaire JavaDoc


/** * Cette classe contient une m ethode additionner. */ public class Truc { /** * Retourne la somme des deux valeurs * sp ecifi ees en parametre. * @param a la premi` ere valeur. * @param b la deuxi` eme valeur. * @return la somme des deux valeurs. */ public int additionner(int a, int b) { return a+b; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 330 / 379

Java

Cours 10

R esultat du commentaire pr ec edent

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

331 / 379

Java

Cours 10

R esultat du commentaire pr ec edent

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

332 / 379

Java

Cours 10

Les tags disponibles


@author @docRoot @deprecated @link @param @return @see @since @throws @version @exception @serial @serialData @serialField 1.0 1.3 1.0 1.2 1.0 1.0 1.0 1.1 1.2 1.0 1.0 1.2 1.2 1.2 pour pr eciser lauteur de la fonctionnalit e chemin relatif qui m` ene ` a la racine de la doc. indique que le membre ou la classe est d epr eci ee permet de cr eer un lien pour d ecrire un param` etre pour d ecrire la valeur de retour pour ajouter une section Voir aussi depuis quelle version la fonctionnalit e est disponible pour indiquer les exceptions jet ees par les m ethodes pour indiquer la version de la classe synonyme de @throws (pour la s erialisation) (pour la s erialisation) (pour la s erialisation)
Programmation Orient ee Objet 29 mai 2012 333 / 379

Bertrand Estellon (DIL Aix-Marseille)

Java

Cours 10

Commentaire dune classe ou dune interface


/** * Une classe truc qui permet dadditionner * Par exemple : * <pre> * Truc truc = new Truc(); * int b = truc.additionner(3, 6); * </pre> * * @author Bertrand Estellon * @version 1.0 * @see java.lang.String */ public class Truc { .... }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 334 / 379

Java

Cours 10

Commentaire dune classe ou dune interface

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

335 / 379

Java

Cours 10

Commentaire des champs


public class Position { /** * La coordonn ee X. * * @see #getPoint() */ public int x = 12; /** * La coordonn ee Y. * * @see #getPoint() */ public int y = 40; .... }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 336 / 379

Java

Cours 10

Commentaire des champs

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

337 / 379

Java

Cours 10

Commentaire des m ethodes


/** * Returns the character at the * specified index. An index ranges from * <code>0</code> to <code>length() - 1</code>. * * @param index the index of the desired character. * @return the desired character. * @throws StringIndexOutOfRangeException * if the index is not * in the range <code>0</code> * to <code>length()-1</code>. * @see java.lang.Character#charValue() */ public char charAt(int index) { .... }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 338 / 379

Java

Cours 10

Commentaire des m ethodes

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

339 / 379

Java

Cours 10

Int egration dans les IDE

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

340 / 379

Java

Cours 10

G en eration de la documentation
Avec Eclipse ou NetBeans :

En ligne de commande avec la commande javadoc


Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 341 / 379

Java

Cours 10

Documentation dun projet...

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

342 / 379

Java

Cours 10

R evision Les mots r eserv es...


Gestions des paquets : package import D enitions des classes, interfaces et enum erations : class interface enum H eritage : extends implements
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 343 / 379

Java

Cours 10

R evision Classes
class UneClasse { int field1; String field2; UneClasse(int p1) { /* Constructeur de Truc */ field1 = p1; } int method(int p1, int p2) { return p1 + p2 + field1; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 344 / 379

Java

Cours 10

R evision UML Sch ema dune classe

Champ nom : type M ethode nom ( arguments ) : type Arguments argument ( , argument ) * Argument nom : type

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

345 / 379

Java

Cours 10

R evision Interfaces
interface UneInterface { /** Description du comportement de la m ethode. * * @param p1 ... */ void method1(int p1); /** Description du comportement de la m ethode. * * @param p1 ... * @param p2 ... * @return .... */ int method2(int p2, int p3); }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 346 / 379

Java

Cours 10

R evision Impl ementation dune interface


class UneClasse implements UneInterface { String nom; UneClasse(String nom) { this.nom = nom; } void method1(int p1) { System.out.println(p1); } int method2(int p1, int p2) { return p1+p2; }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 347 / 379

Java

Cours 10

R evision Extension dune classe


class UneAutreClasse extends UneClasse { String nom; int prix; UneAutreClasse(String nom, int prix) { super(nom); this.prix = prix; } void method1(int p1) { System.out.println(nom+" : "+p1); } int method3(int p) { return p+prix; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 348 / 379

Java

Cours 10

R evision UML Extensions et impl ementations

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

349 / 379

Java

Cours 10

R evision UML Impl ementation multiples

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

350 / 379

Java

Cours 10

R evision Polymorphisme
Une interface et deux classes qui limpl ementent : interface I { void method(); } class A implements I { void method() { System.out.println("A"); } } class B implements I { void method() { System.out.println("B"); } } Laquelle des deux m ethodes est appel ee ? int test(boolean choix) I i; if (choix) i = new A(); else i = new B(); i.method(); }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 351 / 379

Java

Cours 10

R evision Polymorphisme
Une classe qui etend une classe : class A { void method() { System.out.println("A"); } } class B extends A { void method() { System.out.println("B"); } } Laquelle des deux m ethodes est appel ee ? int test(boolean choix) A a; if (choix) a = new A(); else i = new B(); a.method(); }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 352 / 379

Java

Cours 10

R evision Enum eration

enum Bidule { Truc, Machin, Chose }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

353 / 379

Java

Cours 10

Enum eration (la suite)


Il est possible dassocier de linformation aux valeurs : enum Bidule { Truc ("Truc", 5), Machin ("Machin", 4), Chose ("Chose", 8) private final double nom; private final double prix; Bidule(String nom, int prix) { this.nom = nom; this.prix = prix; } private double nom() { return nom; } private double prix() { return prix; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 354 / 379

Java

Cours 10

Enum eration (la suite)

Utilisation : public static void main(String[] args) { for (Bidule b : Bidule.values()) System.out.printf("Le prix de %s est %d", b.nom(), b.prix()); }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

355 / 379

Java

Cours 10

R evision Les mots r eserv es...

Modicateurs de membres ou de variables : public/protected/private static final abstract synchronized throws

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

356 / 379

Java

Cours 10

R evision modicateur public et packages


Par d efaut, une classe ou une m ethode est non-publique : elle nest accessible que depuis les classes du m eme paquet. Une classe ou un membre publics est accessible de nimporte o` u. Pour rendre une classe ou un membre public : public class ClassePublique { public int proprietePublique ; public void methodePublique ( ) { } } Si chier contient une classe publique, le nom du chier doit etre form e du nom de la classe suivi de .java. Un chier ne peut contenir quune seule classe publique.
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 357 / 379

Java

Cours 10

R evision modicateur private et encapsulation


Un membre priv e nest accessible que par les m ethodes de la classe qui le contient. Pour rendre un membre priv e, on utilise le modicateur private : public class ClassePublique { private int proprietePrivee ; private void methodePrivee ( ) { } } Encapsulation : Tout ce qui participe ` a limpl ementation des services doit etre priv e (an de permettre la modication de limpl ementation des services sans risquer dimpacter les autres classes)

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

358 / 379

Java

Cours 10

R evision modicateur protected et h eritage


Un membre prot eg e est accessible depuis :
les m ethodes de la classe qui le contient ; des m ethodes des classes qui etendent la classe qui le contient.

Pour rendre un membre prot eg e, on utilise le modicateur protected : public class ClassePublique { protected i n t p r o p r i e t e P r o t e g e e ; protected void methodeProtegee ( ) { } } Utilisation possible : Commencer limpl ementation dun service dans une classe et la terminer dans les classes qui l etendent . Interpr etation : Les membres prot eg es forment une interface entre une classe et les classes qui l etendent.
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 359 / 379

Java

Cours 10

R evision UML Visibilit e

# +

: : : :

priv e (private ) prot eg e (protected ) publique (public ) non-publique (default )

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

360 / 379

Java

Cours 10

R evision Donn ees et m ethodes statiques


Les m ethodes et des donn ees statiques sont directement associ ees ` a la classe (et non aux instances de la classe) : class Compteur { private static int cpt = 0; static void compte() { cpt++; } static int valeur() { return cpt; } } Utilisation : Compteur.compte(); Compteur.compte(); Compteur.compte(); System.out.println(Compteur.valeur());
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 361 / 379

Java

Cours 10

R evision Classes abstraites

abstract class A { abstract int prix(); void afficherPrix() { System.out.println(prix()); }; } class B extends A { int prix() { return 5; } } class C extends A { int prix() { return 10; } }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

362 / 379

Java

Cours 10

R evision Classes abstraites


Les deux classes B et C h eritent de la m ethode acherPrix() : B b = new B(); C c = new C(); b.afficherPrix(); c.afficherPrix(); Classes abstraites et polymorphisme : A a; if (choix) a = new B(); else a = new C(); a.afficherPrix();

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

363 / 379

Java

Cours 10

R evision Les mots r eserv es...


Dans le code : if/else for do/while switch/case/default continue/break try/catch/finally throw return new null false true this super
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 364 / 379

Java

Cours 10

R evision this
class Machin { private String nom; private int prix; public Machin(String nom, int prix) { this.nom = nom; this.prix = prix; } int ajouterPrix(int prix) { return prix + this.prix; } }

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

365 / 379

Java

Cours 10

R evision super
class Truc { private String nom; public Truc(String nom) { this.nom = nom; } public String toString() { return nom; } } class Machin extends Truc { private int prix; public Machin(String nom, int prix) { super(nom); this.prix = prix; } public String toString() { return super.toString() + " "+prix; } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 366 / 379

Java

Cours 10

R evision Exceptions
Elles etendent Exception et on les jette avec le mot-cl e throw : throw new MyException("truc"); On les captures avec try/catch : try { ... } catch(MyException e) { ... } On les fait remonter avec throws : void method() throws MyException { ... }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 367 / 379

Java

Cours 10

R evision Les mots r eserv es...

Les types simples : boolean byte char short int long double float void

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

368 / 379

Java

Cours 10

R evision Les types primitifs

byte short int long oat double char boolean

entier entier entier entier otant otant caract` ere boolean

8 bits 16 bits 32 bits 64 bits 32 bits 64 bits 16 bits 1 bit

-128 ` a 127 -32768 ` a 32767 231 231 1 263 263 1

caract` eres Unicode false ou true

0 0 0 0 0.0 0.0 \u0000 false

int a = 12; double b = 1 3 . 5 ;

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

369 / 379

Java

Cours 10

R evision Structures de donn ees Java


Des interfaces : Collection<V> : Groupe d el ements
List<V> : Liste d el ements ordonn es et accessibles via leur indice Set<V> : Ensemble d el ements uniques Queue<V> : Une le d el ements (FIFO) Deque<V> : Une le ` a deux bouts (FIFO-LIFO)

Map<K,V> : Ensemble de couples cl e-valeur. Il est pr ef erable dutiliser les interfaces pour typer les variables : L i s t < I n t e g e r > l = new A r r a y L i s t < I n t e g e r > ( ) ; (code qui utilise l) car on peut changer la structure de donn ees facilement : L i s t < I n t e g e r > l = new L i n k e d L i s t < I n t e g e r > ( ) ; (code qui utilise l et qui na pas ` a etre modi e)
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 370 / 379

Java

Cours 10

R evision Structures de donn ees Java


Impl ementations de List<V> : ArrayList<V> : Tableau dont la taille varie dynamiquement. LinkedList<V> : Liste cha n ee. Stack<V> : Pile (mais une impl ementation de Deque est pr ef erable). Impl ementations de Map<K,V> : HashMap : table de hachage LinkedHashMap : table de hachage + listes chain ees TreeMap : arbre rouge-noir (Les el ements doivent etre comparables) Impl ementations de Set<V> : HashSet<V> : avec une HashMap. LinkedHashSet<V> : avec une LinkedHashMap. TreeSet<V> : avec une TreeMap. Impl ementations de Deque<V> : ArrayDeque<V> : avec un tableau dynamique. LinkedList<V> : avec une liste cha n ee.
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 371 / 379

Java

Cours 10

R evision Boxing et unboxing


Liste dentiers : List<Integer> liste = new ArrayList<Integer>(); Il faut utiliser la classe demballage Integer associ e au type simple int : int i = 2; Integer j = new Integer(i); p.empiler(j); Integer k = p.depiler(); int l = j.intValue(); Depuis Java 5, autoboxing et auto-unboxing : int i = 2; p.empiler(i); int l = p.depiler(); (Attention : des allocations sont eectu ees sans new dans le code)
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 372 / 379

Java

Cours 10

R evision Classes demballage


Les classes demballage associ es aux types simples : Number : classe abstraite pour les nombres
Byte : public Byte(byte b) Short : public Short(short s) Integer : public Integer(int i) Long : public Long(long l) Float : public Float(oat f) Double : public Double(double d)

Boolean : public Boolean(boolean b) Character : public Character(char c) Cr eation et utilisation dune liste de bool eens : List<Boolean> liste = new ArrayList<Boolean>(); liste.add(true);
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 373 / 379

Java

Cours 10

R evision Classes g en eriques


D enition dune classe g en erique : class MaClasseGenerique<T> { void method1(T e) { ... } T method2() { ... } } Condition sur les param` etres : class MaClasseGenerique<T extends Comparable<T>> { ... } Type ? super T et ? extends T : class MaClasseGenerique<T> { void method1(? super T p1, ? extends T p2) { ... } }
Bertrand Estellon (DIL Aix-Marseille) Programmation Orient ee Objet 29 mai 2012 374 / 379

Java

Cours 10

R evision Les mots r eserv es...

Les autres mots r eserv es de Java : assert goto native assert strictfp volatile instanceof transient

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

375 / 379

Java

Cours 10

R evision Les cinq principes SOLID


Single Responsibility Principle (SRP) :
Une classe ne doit avoir quune seule responsabilit e

Open/Closed Principle (OCP) :


Programme ouvert pour lextension, ferm e` a la modication

Liskov Substitution Principle (LSP) :


Les sous-types doivent etre substituables par leurs types de base

Interface Segregation Principle (ISP) :


Eviter les interfaces qui contiennent beaucoup de m ethodes

Dependency Inversion Principle (DIP) :


Les modules dun programme doivent etre ind ependants Les modules doivent d ependre dabstractions

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

376 / 379

Java

Cours 10

R evision Patrons de conception


Les patrons de conception d ecrivent des solutions standards pour r epondre aux probl` emes rencontr es lors de la conception orient ee objet Il tendent ` a respecter les 5 principes SOLID Ils sont le plus souvent ind ependants du langage de programmation Ils ont et e formalis es dans le livre du Gang of Four ( Erich Gamma, Richard Helm, Ralph Johnson et John Vlissides 1995) Les patrons orent la possibilit e de capitaliser un savoir pr ecieux n e du savoir-faire dexperts (Buschmann 1996) Les anti-patrons (ou antipatterns) sont des erreurs courantes de conception.

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

377 / 379

Java

Cours 10

Les utilisations de Java...

Interfaces graphiques (Swing, AWT, SWT...) Applications r eseaux (Int eraction avec le r eseau, RMI, s ecurit e, ...) Site Web (JFace, JSP, DOM, Servlets, GWT...) Gestion des formats de donn ees (XML, Excels...) Bases de donn ees (JDBC, JDO, Hibernate...) Gestion des tests unitaires (JUnit) Application sur t el ephones mobiles (J2ME, Android...) ... Pour utiliser ces technologies, les concepts de POO sont indispensables

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

378 / 379

Java

Cours 10

Les autres langages ` a objets...

C++ : tr` es utilis e Objective C : langage utilis e par Apple (IPhone, IPad...) ActionScript : langage dAdobe (Flash) C# : langage de Microsoft (.NET, SilverLight) PHP : langage tr` es utilis e sur le Web Python Ruby Pour utiliser ces langages, les concepts de POO sont indispensables La syntaxe change mais les concepts de POO sont les m emes

Bertrand Estellon (DIL Aix-Marseille)

Programmation Orient ee Objet

29 mai 2012

379 / 379

S-ar putea să vă placă și