Understanding java-1.5 inheritance from scratch (2)
Next, let's continue to introduce inheritance.
1. Sequence of methods to be searched when subclass calls a method:
Let's continue with the animal code in the previous chapter as an example:
package com.ray.ch01;public class Animal {private String name;private long id;private String location;public void eat() {System.out.println(animal is eating);}public void sleep() {}}
package com.ray.ch01;public class Bird extends Animal {@Overridepublic void eat() {System.out.println(bird is eating);}public static void main(String[] args) {Animal bird = new Bird();bird.eat();}}
Output:
Bird is eating
package com.ray.ch01;public class Dog extends Animal {public static void main(String[] args) {Animal dog = new Dog();dog.eat();}}
Output:
Animal is eating
Let's first look at the class diagram:
The sequence of calling methods is clear based on the class diagram:
1) Find the class in the implementation class, that is, the class behind new. If not, go to 2.
2) Go to the parent class to find the parent class. Keep searching for the parent class in this loop until it is found. Otherwise, an error is returned.
2. Main Points of inheritance.
(1) subclass is derived from the extend parent class.
(2) subclass inherits the methods and instance variables of the parent class public and protected, but does not inherit private.
(3) inherited methods can be overwritten, but instance variables cannot.
(4) Verify the rationality of inheritance through the is-a test.
(5) the is-a relationship is unidirectional. Birds are animals, but animals are not necessarily birds.
(6) When a method is overwritten, the method to be overwritten is called first.
(7) If x is the parent class of y and y is the parent class of z, x is also the parent class of z.
3. is-a and is-like-
"Yes" and "like"
Let's look at the class chart above and compare it with the class chart of the previous animals. This class chart has more sub-classes than others.
In our opinion, the class picture of animals is completely replaced. There is no other method in the subclass, which is an ideal inheritance method. However, in the real world, you often need to add your own unique methods in the new category. In this case, you can only say "like one", rather than "as one". Of course, this is also an inheritance method, but it is not so absolute replacement, but it is more suitable for practical needs.
Summary: This chapter discusses the search sequence of calling subclass methods and the inheritance relationship.
This chapter is here. Thank you.