2017-02-25 4 views
1

Ist ich richtig gedacht? Ich erkläre es in Code Behide //Über Casting-Objekt

Ich lese darüber aus vielen Web aber immer noch verwirren. Danke für jede Hilfe :)

Das ist alles, was wir haben.

( class Test

Klasse Tier

Klasse Säugetier erstreckt

Tier

Klasse Katze Säugetier

Klasse erweitert Hund erstreckt Säugetier

)

 public static void main(String args[]){ 
     Test test = new Test(); 
     Cat c = new Cat(); // Create object Cat, Now variable c refer to Cat. 

     System.out.println(c.type); 
     c.thisIs(); 
     c.getType(); 
     test.instanceofAllType(c); 
     c.giveMilk(c); 
     test.line(); 

     Animal a = c; //It still refer to Object Cat but compiler see it as Animal. 
     System.out.println(a.type); 
     a.thisIs(); 
     a.getType(); 
     test.instanceofAllType(a); 
        //a.giveMilk(a); Can't use. We don't see method giveMilk() from variable type Animal. 
     test.line(); 

     c = (Cat)a; //Compiler see it as Cat as first because we (cast) it back. 
     System.out.println(c.type); 
     c.thisIs(); 
     c.getType(); 
     test.instanceofAllType(c); 
     c.giveMilk(c); //We can see and use method giveMilk() again. 
     test.line(); 
    } 
} 

Dies ist Ausgabe

Cat 
This is a Cat 
Type =Cat 
Yes ,I'm Animal! 
Yes ,I'm Mammal! 
Yes ,I'm Cat! 
No ,I'm not a Dog 
I'm a cat and i get a milk. 
========================== 
Animal 
This is a Cat 
Type =Cat 
Yes ,I'm Animal! 
Yes ,I'm Mammal! 
Yes ,I'm Cat! 
No ,I'm not a Dog 
========================== 
Cat 
This is a Cat 
Type =Cat 
Yes ,I'm Animal! 
Yes ,I'm Mammal! 
Yes ,I'm Cat! 
No ,I'm not a Dog 
I'm a cat and i get a milk. 
========================== 
+1

Yup! Sieht gut aus. –

+0

Was genau ist deine Frage? –

+0

Meine Frage ist woran ich denke (Casting) ist richtig oder falsch. @Joe C – Erick

Antwort

0

Sie sind meist richtig. Dies ist jedoch ein bisschen falsch:

 c = (Cat)a; //Compiler see it as Cat as first because we 
        //(cast) it back. 

Der Compiler weiß nicht, dass a auf eine Cat bezieht. Es weiß, dass es könnte beziehen sich auf eine Cat. Der Compiler weiß, dass das Ergebnis von (Cat) a ein Cat (oder null) genau dann ist, wenn die Typumwandlung zur Laufzeit erfolgreich ist. Wenn die Typumwandlung nicht erfolgreich ist, wird (zur Laufzeit) eine Ausnahme ausgelöst und die Zuweisung an c wird nicht ausgeführt.

Kurz gesagt, der Compiler weiß nicht genau, was passieren wird, aber er weiß, dass die Berechnung die Java-Typsicherheitsregeln erfüllt.