Home Java javaTutorial Understand static binding and dynamic binding in Java

Understand static binding and dynamic binding in Java

Dec 26, 2016 pm 04:07 PM

The execution of a Java program requires two steps: compilation and execution (interpretation). At the same time, Java is an object-oriented programming language. When the subclass and the parent class have the same method, and the subclass overrides the method of the parent class, when the program calls the method at runtime, should it call the method of the parent class or the overridden method of the subclass? This should be the question when we first learn Java. problems encountered. Here first we will determine which method to call or the operation of variables is called binding.

There are two binding methods in Java, one is static binding, also called early binding. The other is dynamic binding, also known as late binding.

The concept of program binding:

Binding refers to the association of a method call with the class (method body) in which the method is located. For Java, binding is divided into static binding and dynamic binding; or early binding and late binding

Static binding (early binding compiler binding):

The method has been bound before the program is executed, which is implemented by the compiler or other linker. For example: C. For Java, it can be understood as binding during program compilation; in particular, the only methods in Java are final, static, private and constructor methods, which are early binding

dynamic binding (late binding runtime binding) ):

Late binding: Binding is performed at runtime based on the type of the specific object.

If a language implements late binding, it must also provide some mechanism to determine the type of the object during runtime and call the appropriate methods respectively. That is to say, the compiler still does not know the type of the object at this time, but the method calling mechanism can investigate by itself and find the correct method body. Different languages ​​implement late binding differently. Think of it this way: They all have to insert some special type of information into the object.

The process of dynamic binding:

The virtual machine extracts the method table of the actual type of the object

The virtual machine searches for the method signature

Calls the method

Summary on binding:

After understanding the concepts of the three, we found that java belongs to late binding. In Java, almost all methods are late bound. Dynamically bound methods belong to subclasses or base classes at runtime. But there are also special ones. Since static methods and final methods cannot be inherited, their values ​​can be determined at compile time. They are early binding. A special point to note is that methods and member variables declared privately cannot be inherited by subclasses. All private methods are implicitly designated as final (from this we know: declaring methods as final type is to prevent the method from being overwritten. , the second is to effectively turn off dynamic binding in java). Late binding in Java is implemented by the JVM. We do not need to declare it explicitly, but C++ is different. We must explicitly declare that a method has late binding. Upcasting or polymorphism in Java is achieved with the help of dynamic binding, so understanding dynamic binding means upcasting and polymorphism.

For methods in Java, except for final, static, private and constructor methods, which are pre-bound, all other methods are dynamically bound. Dynamic binding typically occurs under the conversion statement between the parent class and the subclass:

For example: Parent p = new Children();

The specific process is as follows:

1. The compiler checks the declared type and method name of the object. Suppose we call the x.f(args) method, and x has been declared as an object of class C, then the compiler will enumerate all methods named f in class C and the f methods inherited from the super class of class C

2. Next, the compiler checks the parameter types provided in the method call. If among all the methods named f, there is a parameter type that best matches the parameter type provided by the call, then this method is called. This process is called "overload resolution"

3. When the program is running and uses dynamic When a binding calls a method, the virtual machine must call a version of the method that matches the actual type of the object pointed to by x. Assume that the actual type is D (a subclass of C). If class D defines f(String), then this method is called. Otherwise, the method f(String) is searched for in the superclass of D, and so on

Problem thinking:

How to provide method users with a method to complete a task. What if the user has special requirements and can he customize his own method?

Involved knowledge:

Child and parent classes, interfaces, upward transformation, dynamic binding

Specific code:

package com.chengxuyuanzhilu;
 
public interface MyInterfaces {
  void doting();
}
 
 
 
package com.chengxuyuanzhilu;
 
public class Drink implements MyInterfaces {
 
  @Override
  public void doting() {
    System.out.println("我在喝水");
  }
 
}
 
 
 
package com.chengxuyuanzhilu;
 
public class Eat implements MyInterfaces {
 
  @Override
  public void doting() {
    System.out.println("我在吃东西");
  }
 
}
 
 
 
package com.chengxuyuanzhilu;
 
public class Run implements MyInterfaces {
 
  @Override
  public void doting() {
    System.out.println("我在奔跑");
  }
 
}
 
 
 
package com.chengxuyuanzhilu;
 
public class TestDynamicBind {
  public static void main(String[] args) {
    MyInterfaces my = null;
    my = new Eat();
    bind(my);
     
    my = new Drink();
    bind(my);
     
    my = new Run();
    bind(my);
         
  }
   
  static void bind(MyInterfaces my){
    my.doting();
  }
}
Copy after login

The above is the entire content of this article, I hope it will be helpful to everyone's study.

For more articles related to understanding static binding and dynamic binding in Java, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1263
29
C# Tutorial
1236
24
Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

See all articles