1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
public class Conteneur {
private final String name;
public Conteneur (String pName) {
this.name = pName;
}
public class Intern {
public void method() {
// Une classe interne a accès a la reference du conteneur
System.out.println ( "Intern : " + Conteneur.this.name );
}
}
public static class StaticIntern {
public void method(Conteneur conteneur) {
// Une classe interne static a accès aux éléments private
// Mais elle n'est pas lié à une reference d'un objet.
// On ne peut donc pas utiliser Conteneur.this
System.out.println ( "StaticIntern : " + conteneur.name );
}
}
public Intern getIntern () {
// Intern est lié à l'instance courante du Conteneur
return new Intern();
}
public StaticIntern getStaticIntern () {
// StaticIntern est indépendante de l'instance courante
return new StaticIntern();
}
public static void main (String[] args) {
Conteneur c1 = new Conteneur("C1");
Conteneur c2 = new Conteneur("C2");
Intern intern = c1.getIntern();
StaticIntern staticIntern = c1.getStaticIntern();
intern.method(); // affichera C1 car les classes sont liés
staticIntern.method(c1); // affichera C1 car on le passe en paramètre
// mais les deux classes ne sont pas lié...
c2.getIntern().method(); // affichera C2
c2.getStaticIntern().method(c1); // affichera C1
}
} |