Java中的静态绑定与动态绑定

在继续讨论和实现Java中的静态和动态绑定之前,需要记住一些关键点,稍后我们将讨论和实现Java中的静态和动态绑定,并总结它们的区别。

null
  • 私有、最终和静态成员(方法和变量)使用静态绑定,而对于虚拟方法(在Java中,默认情况下方法是虚拟的),绑定是在运行时基于运行时对象完成的。
  • 静态绑定使用类型信息进行绑定,而动态绑定使用对象解析绑定。
  • 重载方法使用静态绑定进行解析(当有多个同名方法时,决定调用哪个方法),而重写方法使用动态绑定,即在运行时。

静态绑定

编译器可以在编译时解析的绑定称为静态绑定或早期绑定。所有静态、私有和最终方法的绑定都在编译时完成。

例子:

JAVA

// Java Program to Illustrate Static Binding
// Main class
class NewClass {
// Static nested inner class
// Class 1
public static class superclass {
// Method of inner class
static void print()
{
// Print statement
System.out.println(
"print() in superclass is called" );
}
}
// Static nested inner class
// Class 2
public static class subclass extends superclass {
// Method of inner class
static void print()
{
// print statement
System.out.println(
"print() in subclass is called" );
}
}
// Method of main class
// Main driver method
public static void main(String[] args)
{
// Creating objects of static inner classes
// inside main() method
superclass A = new superclass();
superclass B = new subclass();
// Calling method over above objects
A.print();
B.print();
}
}


输出

print() in superclass is calledprint() in superclass is called

输出说明: 如您所见,在这两种情况下,都会调用超类的print方法。让我们讨论一下这是如何发生的

  • 我们已经创建了一个子类的对象和一个超类的对象以及超类的引用。
  • 由于超类的print方法是静态的,编译器知道它不会在子类中被重写,因此编译器知道在编译时调用哪个print方法,因此没有歧义。

作为练习, 这个 读者可以将对象B的引用更改为子类,然后检查输出。

动态绑定

在动态绑定中,编译器不决定要调用的方法。重写是动态绑定的完美例子。在重写中,父类和子类都有相同的方法。

例子:

JAVA

// Java Program to Illustrate Dynamic Binding
// Main class
public class GFG {
// Static nested inner class
// Class 1
public static class superclass {
// Method of inner class 1
void print()
{
// Print statement
System.out.println(
"print in superclass is called" );
}
}
// Static nested inner class
// Class 2
public static class subclass extends superclass {
// Method of inner class 2
@Override void print()
{
// Print statement
System.out.println(
"print in subclass is called" );
}
}
// Method inside main class
public static void main(String[] args)
{
// Creating object of inner class 1
// with reference to constructor of super class
superclass A = new superclass();
// Creating object of inner class 1
// with reference to constructor of sub class
superclass B = new subclass();
// Calling print() method over above objects
A.print();
B.print();
}
}


输出

print in superclass is calledprint in subclass is called

输出说明: 这里的输出不同。但为什么呢?让我们把代码分解并彻底理解它。

  • 在这段代码中,方法不是静态的。
  • 在编译过程中,编译器不知道必须调用哪个print,因为编译器只通过引用变量而不是对象的类型,因此绑定将延迟到运行时,因此将根据对象的类型调用相应版本的print。

提示: 极客们,现在问题来了,为什么静态、最终和私有方法的绑定总是静态绑定?

静态绑定的性能更好(不需要额外的开销)。编译器知道所有这些方法 不能被覆盖 并且始终由本地类的对象访问。因此,编译器在确定类的对象(当然是本地类)时没有任何困难。这就是为什么这些方法的绑定是静态的。

现在让我们终于看到 静态绑定和动态绑定之间的区别 具体如下:

静态绑定 动态绑定
它发生在被称为早期绑定的编译时 它发生在运行时,因此被称为后期绑定。
它更精确地使用重载运算符重载方法 它使用覆盖方法。
它使用正常函数进行 它是通过虚拟函数实现的
真实对象从不使用静态绑定 真实对象使用动态绑定。

本文由 Rishabh Mahrsee。 如果你喜欢GeekSforgeks,并且想贡献自己的力量,你也可以写一篇文章,然后把你的文章邮寄给评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享