静态与动态绑定逻辑 [英] Static vs Dynamic Binding Logic

查看:95
本文介绍了静态与动态绑定逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

import java.lang.*;

public class Program
{
    public static void main(String [] args) 
    { 
        B a = new A(); 

        a.p(10);  
        a.p(10.0); 
    } 
} 
    class B { 
        public void p(double i) 
        { 
            System.out.println(i*2); 
        } 
    }

    class A  extends B{ 
        public void p(int i) 
        { 
            System.out.println(i); 
        } 
    } 

当我使用 B a = new A(),在两种情况下都得到20.0这是有意义的,因为重载是编译期间的句柄,编译器查看声明的类型并适当地调用函数。由于我们声明的类型是B类,因此在两种情况下都调用了B类的方法。现在,如果我做 A a = new A(); ,我应该在两个答案中得到10,但我不是。我得到10美元 a.p(10)和20.0美元 a.p(10.0)。基于静态绑定的概念和通过静态绑定完成重载的整个概念,静态绑定查看声明的类型而不是实际类型,为什么结果会以这种方式出现?我非常感谢你的帮助。

When I execute this code using B a = new A() , I get 20.0 in both cases which makes sense because overloading is handles during compile time where the compiler looks at the declared type and calls a function appropriately. Since our declared type was class B, class B's method was called in both cases. Now if I do A a = new A(); , I should be getting 10 in both answers but I am not. I am getting 10 for a.p(10) and 20.0 for a.p(10.0). Based on the concept of static binding and whole notion of overloading being done by static binding which looks at the declared type as opposed to the actual type, why is the result coming out this way ? I would very much appreciate your help.

推荐答案

在你的情况下,你正在进行重载,它将在编译时被绑定(静态绑定。)。静态绑定发生具有引用类型而不是引用所指向的对象类型。
在第一种情况下,你使用的是B的引用变量,并为它指定一个A的对象。由于你的引用是B,即使你使用int,B中的方法p(double)也会静态绑定(因为int可以加宽到一倍)。

In your case, your are doing overloading which will get binded at compile time(static binding.).And static binding happens with type of reference rather than the type of object the reference is pointing. In your first case you are using a reference variable of B and assigning an object of A to it.Since your reference is B, the method p(double) from B will get binded statically even if you use an int(since int can be widened to double).

在第二种情况下,你使用引用作为A本身。在这种情况下,你有两个p()方法可用。一个是来自B的p(双)和来自A.的其他p(int)。因此p(10)将调用p(int)而p(10.0)将调用p(double)

In the second case you are using reference as A itself.In this case, you have two p() methods available.One is p(double) from B and other p(int) from A.So p(10) will call p(int) and p(10.0) will call p(double)

试试这个:

class B { 
    public void p(String i) 
    { 
        System.out.println("parent:"+i); 
    } 
}

class A  extends B{ 
    public void p(int i) 
    { 
        System.out.println(i); 
    } 
} 
public class Test1 {
    public static void main(String args[]) {

         A a = new A(); //arg
            a.p(10);  
            a.p("sample"); 
    }
}

如果将标记为arg的行更改为B a =在新的A()中,你会看到编译器在两种情况下都试图调用父p。

If you change the line marked arg to B a = new A(), you will see compiler trying to call parent p in both the cases.

这篇关于静态与动态绑定逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆