"Head First Java" Reading notes--7 inheritance and polymorphism

Source: Internet
Author: User

(i) Examples of succession

1. Example one:

1Pulicclassdoctor{2         Booleanworksathospital;3         voidtreatpatient () {4             //Perform checks5         }6     }7      Public classFamilydoctorextendsdoctor{8         BooleanMakeshousecalls;9         voidGiveadvice () {Ten             //Make a diagnosis One         } A     } -      Public classSurgeonextendsdoctor{ -         voidtreatpatient () { the             //perform surgery (overriding the method of the parent class) -         } -         voidmakeincision () { -             //amputation +         } -}

  

2, example two: Design the inheritance tree of animal simulation program

There are lions, rhinos, tigers, dogs, cats, wolves, six species of animals, the design process is as follows.
(1) Identify objects that have common attributes and behaviors, and use inheritance to prevent duplicate program code in subclasses; There are 5 instance variables: Picture (the name of the animal's image), food (the animal's diet), hunger (int value representing hunger), boundaries ( Represents the length and width of the area of the animal's activity range), location (the x and y coordinates of the animal in the active area); There are also 4 methods: Makenoise (): The act of making sounds by animals; eat (): The behavior of animals when they encounter things; Sleep (): the act of sleep; roam (): No action procedure during eating or sleeping (note: Roam, stroll)
(2) The design represents the common state and behavior of the class (parent class)--animal,animal contains the common attributes and behavior in the ①;
(3) Decide whether subclasses need to have a particular behavior (that is, the implementation of the method) has a specific way of working, such as for the Eat () method, some animals vegetarian, some animals eat meat, then the different animals will rewrite the parent class of this method.
(4) To find more opportunities for abstraction by finding subcategories of common behaviors, such as cats and tigers and lions belonging to cats, dogs and wolves belong to dogs, then you can abstract cat and canine animals.
(5) Complete the inheritance hierarchy of the class.

  (ii) Inherited method invocation

1. Minimum order principle

When invoking a method of an object reference, it calls to the method closest to the object type, in other words, it looks up from the inheritance tree down to the top, and eventually calls the first satisfied method found, as shown (if the method is not found in the inheritance tree, the compilation will not pass).

2, HAS-A test: Property testing, such as the dog has an age attribute.
Is-a test: Inherit the test, test the rationality of inheritance structure, such as cat is animal->cat extends Animal
Note: The is-a under the concept of inheritance is a one-way relationship, and the direction cannot be reversed. If the cat is an animal, but the animal is not necessarily a cat.

3. If the subclass does not want to completely overwrite a method of the parent class, but instead adds the content to the method of the parent class, you can use super in the method of the subclass, for example:

1  Public classanimal{2      Public voidWalk () {3         //General walk behavior of animal4     }5     //...6 }7  Public classCatextendsanimal{8      Public voidWalk () {9         Super. Walk ();Ten         //Other walk behaviors unique to cat One     } A}

4. Inherited permissions

(1) The following 4 kinds of permissions, the left is the most restricted, the more to the right of the less restrictive degree.
Private default protected public
(2) Members of the public type are inherited, and members of the private type are not inherited. Members of any class contain variables and methods that are defined by themselves, plus anything inherited from the parent class.

 (iii) Other summaries of succession

1, the meaning of inheritance

(1) Avoid duplication of program code;
(2) Define a common agreement, that is, the "contract" between the objects of the class. Inheritance ensures that all classes under a parent type have all inheritable methods held by the parent class.
2. Inheritance vs Combination

(1) The combination is to not use inheritance, but to first create objects of other classes in the class, and then call their methods through the objects of other classes to implement code reuse.
(2) The combination is more flexible than inheritance.
(3) The relationship of "is-a" uses inheritance, such as "birds are animals" birds inherit, inherit animal classes. The "have-a" relationship uses combinations, such as "birds with claws", birds with combinations, and combinations of paw classes.

(iv) The basic concept of polymorphism

1, general Declaration of Reference and creation of the object method: Three-step, the focus is that the reference type and the object type to match, in the following example, both are dog.

(1) Declaring a reference variable (creating a remote control)
(2) Creating objects (creating objects on the heap)
(3) Connecting objects and references (setting the remote control)

2, in polymorphic, the reference and the object can be different types, such as: Animal Mydog = new Dog (); When polymorphism is applied, the reference type can be the parent class of the actual object type.

3. Parameters and return types can also be polymorphic:

1 //parameter polymorphism:2  Public voidDowalk (Animal a) {3 A.walk ();4 }5 //parameter A is a animal type, and when you call the Dowalk method, the parameter can be an object of any subclass of animal. 6 7 //return type polymorphism:8  PublicAnimal getsomething () {9Dog d =NewDog ();Ten     //some code ... One     returnD; A } - //by polymorphism, it is possible to write a program that does not have to be modified when introducing a new subclass. 

4, abide by the contract: the rules of coverage

(1) The parameters must be the same, and the return type must be compatible;
(2) Access to the method cannot be reduced, such as changing from public to private or lowering the permissions.

5. How many layers can the design sub-class design?

A: There is no strict layer rules, but the recommended level is a little bit better.

6. There are three ways to prevent a class from being made sub-class:

The 1th type is access control: Non-public classes can only be subclasses of the same package class;
The 2nd is to use the final decorated class, which means that the class is the end of the inheritance tree and cannot be inherited;
The 3rd is to have the class only have private constructor methods.
Note: Identifying the entire class as final indicates that no method can be overridden.

7. Overloading of methods

(1) Common methods and construction methods can be overloaded.
(2) Definition: Refers to multiple methods in the same class that can be defined with the same name but with different parameters. The corresponding method is selected according to the different parameter tables when calling.
(3) Two with three different: the same class, the same method name, parameter list parameters of the type, number, order of different.
(4) Only the return value type does not constitute an overload! Only parameter names are different and do not make overloads!
(5) Typical method overloads:

1 System.out.println (String str); 2 System.out.println (int  i); 3 System.out.println (double  D); 4 System.out.println ();

8, the method of overloading (overload) and polymorphism: The meaning of overloading is that two methods have the same name, but the parameters are different, so overloading and polymorphism have nothing to do. The overloaded method is not the same as the overridden method.

9, the method of rewriting

(1) With heavy-duty no half-gross money relationship!
(2) A method that inherits from a base class can be overridden in a subclass as needed.
(3) The overriding method must have the same method name, return value, and parameter list as the overridden method.

"End of chapter"

Head First Java book note--7 inheritance and polymorphism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.