Java Casting
Casting

Exercice
Given:1
2
3
4
5
6class X {
  void doStuff() {}
}
class Y {
  void doStuff2() {}
}
and:1
2X x = new Y();
((Y)x).doStuff2();
What is the result?
    A) Compilation fails
    B) Exception at runtime
    C) Y.doStuff2 is executed
Responses : A

When Casting is possible?
Le compilateur verifie certaines regles pour auoriser le Casting
Exercice
Given:1
2
3
4
5
6class X {
  void doStuff() {}
}
class Y extends X {
  void doStuff2() {}
}
and:1
2X x = new X();
((Y)x).doStuff2();
What is the result?
    A) Compilation fails
    B) Exception at runtime
    C) Y.doStuff2 is executed
    D) Some unpredictable behavior
Responses : B //Fails at Runtime : java.lang.ClassCastException



A voir Autoboxing
    Rappel : Le boxing permet de transformer automatiquement une variable de type primitif en un objet de type Wrapper correspondant
    L’unboxing est l’operation inverse
Remarques
- Le Casting peut-être un signe de mauvais design
- Voir pour une class final
- Casting avec une interface