Four. Java inheritance and polymorphism 4. Polymorphic and dynamic binding

Source: Internet
Author: User

In Java, a variable of the parent class can refer to an instance of the parent class, or it can refer to an instance of the child class.

Readers should look at a piece of code first:

  1. Public class Demo {
  2. public static void main(String[] args){
  3. Animal obj = new Animal();
  4. Obj. Cry();
  5. obj = new Cat();
  6. Obj. Cry();
  7. obj = new Dog();
  8. Obj. Cry();
  9. }
  10. }
  11. Class Animal{
  12. //Animal sounds
  13. public void Cry(){
  14. System. Out. println("Do not know how to call");
  15. }
  16. }
  17. Class Cat extends Animal{
  18. //Cat's Cry
  19. public void Cry(){
  20. System. Out. println("Meow meow ~");
  21. }
  22. }
  23. Class Dog extends Animal{
  24. //Barking of dogs
  25. public void Cry(){
  26. System. Out. println("Bark ~");
  27. }
  28. }

Operation Result:
Don't know how to call
Meow Meow ~
Bark ~

The above code defines three classes, namely, Animal, Cat, and Dog,cat, and the Dog class are inherited from the Animal class. The type of the obj variable is Animal, which can point to an instance of the Animal class or to an instance of the Cat and the Dog class, which is correct. That is, a variable of the parent class can refer to an instance of the parent class, or it can refer to an instance of the child class. Note that the reverse is wrong, because all cats are animals, but not all animals are cats.

It can be seen that obj can be either a human or a cat or a dog, it has different manifestations, which is called polymorphism. Polymorphism means that a thing has a different manifestation or form.

Again such as "human", there are many different expression or realization, TA can be a driver, teacher, doctor, etc., you hate yourself when you will say "Next life again," then you become a driver, teachers, doctors can, we say "human" with polymorphism.

There are three prerequisites for polymorphic existence: To have inheritance, to have overrides, to refer to a subclass object as a parent class variable.

When calling a method using Polymorphic mode:

    • First check whether the method is in the parent class, if not, compile the error, and if so, check whether the subclass overrides the method.
    • If the child class overrides the method, the method of the subclass is called, otherwise the parent class method is called.

As can be seen from the above example, one of the benefits of polymorphism is that when subclasses are relatively long, there is no need to define multiple variables, you can define only one variable of a parent class type to refer to instances of different subclasses. Take another look at the following example:

  1. Public class Demo {
  2. public static void main(String[] args){
  3. //With polymorphism, the host can feed many animals
  4. Master ma = new master();
  5. Ma. Feed(new Animal(), new Food());
  6. Ma. Feed(new Cat(), new Fish());
  7. Ma. Feed(new Dog(), new Bone());
  8. }
  9. }
  10. Animal class and its subclasses
  11. Class Animal{
  12. public void eat(food f){
  13. System. Out. println("I am a small animal that is eating" + F. ) Getfood());
  14. }
  15. }
  16. Class Cat extends Animal{
  17. public void eat(food f){
  18. System. Out. println("I'm a kitten, I'm eating" + F. ) Getfood());
  19. }
  20. }
  21. Class Dog extends Animal{
  22. public void eat(food f){
  23. System. Out. println("I'm a dog, I'm eating" + F. ) Getfood());
  24. }
  25. }
  26. Food and its sub-categories
  27. Class Food {
  28. public String getfood(){
  29. return "things";
  30. }
  31. }
  32. Class Fish extends food{
  33. public String getfood(){
  34. return "fish";
  35. }
  36. }
  37. Class Bone extends food{
  38. public String getfood (){
  39. return "Bone";
  40. }
  41. }
  42. Master Class
  43. Class Master{
  44. public void feed(Animal A, food f){
  45. An. Eat(f);
  46. }
  47. }

Operation Result:
I am a small animal, eating things
I'm a little kitty, I'm eating fish.
I'm a dog, eating bones.

The Master class's Feed method has two parameters, namely the Animal type and the food type, because it is the parent class, so you can pass an instance of the subclass to it so that the master class does not need multiple methods to feed the different animals.

Dynamic binding

To understand the nature of polymorphism, let's talk about the detailed flow of Java invocation methods.

1) The compiler looks at the declaration type and method name of the object.

Assume that you call Obj.func (param), and obj is an object of the Cat class. It is important to note that there may be multiple methods with the name Func but not the same parameter signature. For example, there may be method func (int) and func (String). The compiler will enumerate through all the methods named Func in all Cat classes and its parent class Animal, which has a public access property called Func.

In this way, the compiler obtains a list of all the candidate methods that might be called.

2) Next, the codec will check the parameter signature provided when calling the method.

Select this method if there is a method in all methods named Func that exactly matches the supplied parameter signature. This process is called overload resolution (overloading resolution). For example, if you call func ("Hello"), the compiler chooses the func (String) instead of the func (int). Because of the existence of an automatic type conversion, such as an int that can be converted to a double, if no method is found that is the same as calling the method parameter signature, the type conversion is performed and then the lookup continues, if there is no matching type at all, or if more than one method matches it, then the compilation error.

In this way, the compiler obtains the method name and parameter signatures that need to be called.

3) If the modifier of a method is private, static, final (static and final will be explained later), or is a constructor method, then the compiler will be able to know exactly which method should be called, and we call this called static binding binding).

By contrast, the method that is called relies on the actual type of the object and implements dynamic binding at run time. For example, if func ("Hello") is called, the codec will generate an instruction called Func (String) in a dynamically bound manner.

4) When the program is running and the method is invoked with dynamic binding, the JVM must invoke the method of the class that is most appropriate for the actual type of the object referenced by obj. We have assumed that the actual type of obj is cat, which is a subclass of Animal, which is called if Func (String) is defined in cat, otherwise it will be found in the Animal class and its parent class.

Each time the method is called for a search, the overhead is considerable, so the JVM has previously created a method lable for each class that lists the names of all the methods, the parameter signatures, and the classes to which they belong. This way, when the method is actually called, the virtual machine looks for the table only. In the example above, the JVM searches the Cat class's method table to find a method that matches the call to func ("Hello"). This method may be either Cat.func (string) or Animal.func (string). Note that if you call Super.func ("Hello"), the compiler will search the method table of the parent class for a row.

Assuming that the Animal class contains the three methods of Cry (), GetName (), Getage (), then its method table is as follows:
Cry (), Animal.cry ()
GetName (), Animal.getname ()
Getage (), Animal.getage ()

In fact, Animal also has the default parent class object (which will be explained later), which inherits the method of object, so the methods listed above are not complete.

Assuming the Cat class overrides the Cry () method in the Animal class, and a new method Climbtree () is added, its argument list is:
Cry (), Cat.cry ()
GetName (), Animal.getname ()
Getage (), Animal.getage ()
Climbtree (), Cat.climbtree ()

At run time, the process of calling the Obj.cry () method is as follows:

      • The JVM first accesses the method table of the actual type of obj, possibly a method table for the Animal class, or a method table for the Cat class and its subclasses.
      • The JVM searches the method table for a method that matches the cry () and, when found, knows which class it belongs to.
      • The JVM calls the method.

Four. Java inheritance and polymorphism 4. Polymorphic and dynamic binding

Related Article

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: 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.