Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static vs Dynamic Binding Logic

Tags:

java

I have the following code:

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); 
        } 
    } 

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.

like image 314
Stranger Avatar asked Dec 20 '25 09:12

Stranger


2 Answers

An int can be widened to a double, but not the other way around. This means that 10 can call B.p(double) or A.p(int) but 10.0 is a double and will not be implicitly converted to an int i.e. only B.p(double) will be called.

like image 178
Peter Lawrey Avatar answered Dec 22 '25 23:12

Peter Lawrey


Its because your method p is not an overridden method, it is just inhereted in your sub-class when you use

Super sup = new Sub();
sup.p(int);
sup.p(double);

In this case as your Super class has a method which takes double as a parameter and aa an int can fit into a double your Super-class's method is invoked the one which accepts double.

Sub sup = new Sub();
sup.p(int);
sup.p(double);

In this case however, as your subclass doesn't have a method which takes a double, for sup.p(double) call it uses the inherited method from super class if you pass double as an argument.

like image 20
PermGenError Avatar answered Dec 22 '25 23:12

PermGenError