6.Java polymorphism 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.

Please read the code first:

  1. Public class Demo {
  2. public static void main(String[] args) {
  3. people obj = new people(); //Referencing the parent class instance
  4. Obj. Say();
  5. obj = new Teacher(); //reference Subclass instance
  6. Obj. Say();
  7. }
  8. }
  9. Class people{
  10. void say(){
  11. System. Out. println("Hello, I am a good citizen");
  12. }
  13. }
  14. Class Teacher extends people{
  15. void say(){
  16. System. Out. println("Hello, I am a teacher");
  17. }
  18. }

Operation Result:
Hello, I'm a good citizen.
Hi, I'm a teacher.

The above code defines two classes, namely the people and Teacher,teacher classes, which inherit from the People class. The type of the obj variable is people, which can point to an instance of the people class or to an instance of the Teacher 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 teachers are human, but not all of them are teachers.

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

Again, such as "pet", there are many different expressions or implementations, it can be kittens, puppies, lizards, etc., we went to the pet shop said "Please give me a pet", waiter give us kittens, puppies or lizards can, we say "pet" 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.
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 Obj.func (param) is called, and obj is an object of the Teacher 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 the Teacher class and its parent class, people, that has access to the public property named 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 calledoverload 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 the method is private, static, final (static and final will be explained later), or is a constructor, then the compiler will be able to know exactly which method should be called, and we call this calledstatic bindings (statically 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 Teacher, which is a subclass of people, which is called if Func (String) is defined in Teacher, otherwise it will be found in the people class and its parent class.

Every time the method is called to search, the overhead is quite large, so the JVM has created a pre-set for each classMethods Table (method lable), which lists the names of all methods, parameter signatures, and the classes that belong to them. This way, when the method is actually called, the virtual machine looks for the table only. In the example above, the JVM searches the method table of the Teacher class to find a method that matches the invocation of func ("Hello"). This method may be either Teacher.func (string) or People.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 people class contains say (String), GetName (), and Getage () three, its method table is as follows:
Say (String), People.say (String)
GetName (), People.getname ()
Getage (), People.getage ()

In fact, people 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 Teacher class overrides the GetName () method in the People class, and a new method Raisesalary (double) is added, its argument list is:
Say (String), People.say (String)
GetName (), Teacher.getname ()
Getage (), People.getage ()
Raisesalary (double), teacher.raisesalary (double)

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

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

6.Java polymorphism and dynamic binding

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.