java静态链接和动态绑定_Java中的静态绑定和动态绑定

java静态链接和动态绑定

Binding is the process of connecting the method call to the method body or determining the type of the object. In Java there are two types of binding, static binding and dynamic binding. I have explained them one by one in this tutorial.

Static Binding in Java

1. When type of the object is determined by the compiler at compile time, it is called as static binding or early binding.
 
2. We can also say that, in static binding the method call is connected to the method body at compile time.
 
3. Static binding occurs when there is any private, final or static method in the class.

Lets take one example to understand static binding in java.

Output

Show
 

As there are no overridden methods so it is obvious that all the methods will be accessed by object of local class (object of Demo). Also the type of the object is determined by the compiler at the compile time therefore static binding occurs in above example.

Static Binding and Dynamic Binding in Java

Static Binding and Dynamic Binding in Java – Image Source

Dynamic Binding in Java

1. When type of the object is determined by the compiler at run time, it is called as dynamic binding or late binding. We can also say that, in dynamic binding the method call is connected to the method body at run time.
 
2. The reference id of a derived class object is stored in reference variable of base class. We can only access the overridden methods, personal methods and variables of derived class can’t be accessed.
 
3. Dynamic binding occurs when there are overridden methods or method overriding.
 

4. Dynamic binding is used to achieve abstraction. We will learn about abstraction in next tutorial.

Lets take one example to understand dynamic binding in java.

Output

Child

As you can see in the above example we are storing the reference id of Child class into the reference variable of Base class. When I have called show() method, the method of Child class is called and the output is “Child”. If Child class contains methods other then show() then they can’t be accessed using variable b. For accessing them we have to either type cast variable b or create another variable of Child class.



I hope that after reading this tutorial the concept of static binding and dynamic binding in java will be clear in your mind. I have also shared a video tutorial that will help you to understand these concepts easily. If you have any doubts and find anything incorrect in above tutorial then please mention it by commenting below.

翻译自: https://www.thecrazyprogrammer.com/2015/04/static-binding-and-dynamic-binding-in-java.html

java静态链接和动态绑定

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值