小编典典

静态与 Java中的动态绑定

java

我目前正在为我的一个类进行分配,在其中,我必须使用Java语法给出 静态动态绑定的 示例。

我了解基本概念,即静态绑定在编译时发生,而动态绑定在运行时发生,但是我无法弄清楚它们实际上是如何工作的。

我找到了一个在线静态绑定的示例,给出了以下示例:

public static void callEat(Animal animal) {
    System.out.println("Animal is eating");
}

public static void callEat(Dog dog) {
    System.out.println("Dog is eating");
}

public static void main(String args[])
{
    Animal a = new Dog();
    callEat(a);
}

并且这将显示“ animal is eating”,因为 对的调用callEat使用了静态绑定,但是我不确定 为什么 将其视为静态绑定。

到目前为止,我所见的任何资料都没有设法以我可以遵循的方式来解释这一点。


阅读 307

收藏
2020-09-08

共1个答案

小编典典

Javarevisited博客文章

这是静态绑定和动态绑定之间的一些重要区别:

  1. Java中的静态绑定发生在编译时,而动态绑定发生在运行时。
  2. privatefinal以及static方法和变量使用静态结合和由编译器所键合而虚拟方法基于运行时对象在运行期间接合。
  3. 静态绑定使用Typeclass在Java中)信息进行绑定,而动态绑定使用对象来解析绑定。
  4. 重载的方法使用静态绑定进行绑定,而重载的方法使用动态绑定在运行时进行绑定。

这是一个示例,可以帮助您理解Java中的静态和动态绑定。

Java中的静态绑定示例

>     public class StaticBindingTest {  
>         public static void main(String args[]) {
>             Collection c = new HashSet();
>             StaticBindingTest et = new StaticBindingTest();
>             et.sort(c);
>         }
>         //overloaded method takes Collection argument
>         public Collection sort(Collection c) {
>             System.out.println("Inside Collection sort method");
>             return c;
>         }
>         //another overloaded method which takes HashSet argument which is
> sub class
>         public Collection sort(HashSet hs) {
>             System.out.println("Inside HashSet sort method");
>             return hs;
>         }
>     }

输出 :内部集合排序方法

Java动态绑定示例

>     public class DynamicBindingTest {  
>         public static void main(String args[]) {
>             Vehicle vehicle = new Car(); //here Type is vehicle but object
> will be Car
>             vehicle.start(); //Car's start called because start() is
> overridden method
>         }
>     }
>  
>     class Vehicle {
>         public void start() {
>             System.out.println("Inside start method of Vehicle");
>         }
>     }
>  
>     class Car extends Vehicle {
>         @Override
>         public void start() {
>             System.out.println("Inside start method of Car");
>         }
>     }

输出: 汽车内部启动方式

2020-09-08