tailieunhanh - head first java second edition phần 4

Đó là thực sự tất cả các tăng cường cho cung cấp cho bạn một cách đơn giản để đi qua tất cả các yếu tố trong bộ sưu tập, nhưng kể từ khi nó sử dụng phổ biến nhất của một vòng lặp, nó là giá trị thêm nó vào ngôn ngữ. Chúng tôi sẽ xem lại LMP enhancedfor trong chương kế tiếp, khi chúng ta nói về bộ sưu tập không phải là mảng. | inheritance and polymorphism Animal The important point is that the reference type AND the object type are the same. In this example both are Dog. These two are NOT the same type- The re-Cerente variable type is Jed-laved as Animal but the objei-t is treated as new 2a These two are the same type- The re-ferente variable type is dedared as Do and the object is treated as new D05O. But with polymorphism the reference and the object can be different. Animal myDog new Dog 0 you are here k 185 polymorphism in action With polymorphism the reference type can be a superclass of the actual object type. When you declare a reference variable any object that passes the IS-A test for the declared type of the reference variable can be assigned to that reference. In other words anything that extends the declared reference variable type can be assigned to the reference variable. This letsyou do things like make polymorphic arrays. OK OK maybe an example will help. aba Animal animals animals 0 new animals 1 new animals 21 new animals 13 new animals 4J new for int i 0 i Hippo 0 Lion DogO Cato Wolf 0 But look what you get to do. you tàn r t AKỲ subclass of Ạnimal in the Animal array here I iz l I of 1L the y u animals . length i e n y d all animals i .eat animals i .roam When V is 0 a Dog is at index 0 in the array so you get the Dog s eato method- When i is I you get the Cat s eato method a e with roâmO- 186 chapter 7 inheritance and polymorphism But wait There s more You can have polymorphic arguments and return types. If you can declare a reference variable of a supertype say Animal and assign a subclass object to it say Dog think of how that might work when the reference is an argument to a method. do horrible things to the Animal at the other end of the a parameter 2 i a r U- u bk Auv 11 VI J rikh. i cr IS rt __ y íkê k - start 0 new Veto naw new DogO TVe oịvtShokỌ Animal rt will work class PetOwner public void Vet V Dog d Hippo h V. giveShot d pos s makefế