search
HomeJavajavaTutorial07.Java Basics - Static Binding & Dynamic Binding

Basic concepts

Binding refers to the association of a method call with the class in which it is located.

Binding can be divided into static binding and dynamic binding.

Several concepts you need to know before analyzing static binding and dynamic binding:

  • Compilation period: The compilation process is to convert the Java source The process of compiling files into bytecode (.class file, JVM executable code). During this process, Java does not deal with memory. During this process, the compiler will perform syntax analysis. If the syntax is incorrect, an error will be reported. .

  • Running period: The running process refers to the JVM (Java virtual machine) loading the bytecode file and interpreting it for execution. This process is the real creation of memory. Execute Java program.


Method calling

The method calling process in Java is as follows:

  • Editor View the object's declared type and method names. Get all candidate methods that may be called due to method overloading. For example: method one is print(String str), method two is print(int).

  • The compiler checks the input parameter type of the calling method. Pick the matching method from the candidate methods. For example, if the input parameter is "hello", select print(String str).

  • If the method is private, static, final, or constructor, the compiler can determine which method to call. This is static binding.

  • If this is not the case, runtime (dynamic) binding must be used.


Static binding

Static binding, also known as early binding and compile-time binding. Indicates binding at compile time, that is, the method has been bound before the program is run.

Only methods, member variables, and constructors modified by final, static, and private are statically bound:

Type Explanation
final The method modified by it can be inherited, but cannot be overridden; subclass objects can be called, but what is called is The method defined in the parent class; indirectly indicating that declaring the method as final can avoid rewriting and turn off dynamic binding.
private The method modified by it implicitly contains the final keyword. Because it is invisible to the outside world, it cannot be inherited or overridden; it can only be called through the object of the class itself, so the object can be clear before the method is run.
static Static methods depend on classes and depend on objects. It can be inherited by subclasses (essentially hidden by subclasses), but cannot be overridden by subclasses. When a subclass object is transformed up to a parent class object, the object will use the static method in the parent class regardless of whether the static method is defined in the subclass. So here it is said that static methods can be hidden.
Member variables By default, Java uses static binding for properties, so that program errors can be discovered during compilation and can provide efficiency.
Construction method The construction method cannot be inherited. When a subclass inherits a parent class, it must first call the parent class's construction method (whether explicit or implicit). Therefore, you can know which object the constructor method refers to before the program is run.

Look at the following example:

// 父类class Parent{    // 变量
    String name="Parent";    // 静态方法
    static void print(){
        System.out.println("Parent print");
    }    // 私有方法
    private void say(){
        System.out.println("Parent say");
    }    // 终态方法
    final void look(){
        System.out.println("Parent look");
    }
}// 子类class Son extends Parent{
    String name ="Son";    static void print(){
        System.out.println("Son print");
    }    // 编译错误,无法重写父类的 final方法
    final void look(){};
}public class Test{
    public static void main(String[] args) {        // 发生向上转型
        Parent p = new Son();        // 输出 Parent
        System.out.println(p.name);        // 输出 Parent print
        p.print();        // 编译错误,对外不可见
        p.say();
    }
}

Dynamic binding

Dynamic binding , also known as late binding and runtime binding; it means binding according to the type of the specific object at runtime.

The process of dynamic binding:

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

  • Virtual machine search Method signature;

  • Call method.

Let’s look at an example:

class A {    int x = 5;
}

class B extends A {    int x = 6;
}

class Parent {    public A getValue() {
        System.out.print("Parent Method ");        return new A();
    }
}

class Son extends Parent {    public B getValue() {
        System.out.print("Son Method ");        return new B();
    }
}public class Test {
    public static void main(String[] args) {        // 向上转型
        Parent p = new Son();        // 输出结果:Son Method 5
        // 注意:是 5 不是 6 !
        System.out.println(p.getValue().x);
    }
}

Observe the output analysis as follows:

  • p.getValue(), due to There is an upward transformation, so it first looks for the method from the subclass (Son), and at this time it calls Son's method. This is dynamic binding.

  • p.getValue( ).x, since x is a member variable, its object (belonging to Parent) is determined before the program is run. Static binding occurs here.

If you still don’t understand, let’s look at an example:

class Parent {
    String name = "Parent " + this.getClass().getName();
}

class Son extends Parent {
    String name = "Son" + this.getClass().getName();
}public class Test {
    public static void main(String[] args) {        // 向上转型
        Parent p = new Son();        // 输出:Parent Son
        System.out.println(p.name);
    }
}

Observe the output and analyze it as follows:

  • p.name : name is a member variable, static binding occurs at this time, so the property of Parent is called.

  • this.getClass( ): getClass is a method. Since an upward transformation occurs at this time, the default program will search for this method starting from the subclass, which happens to also exist in the subclass. Therefore, the method of the subclass is called, and dynamic binding occurs at this time.


The above is the content of 07.Java Basics - Static Binding & Dynamic Binding. For more related content, please pay attention to the PHP Chinese website (www. php.cn)!

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

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

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

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor