简体   繁体   中英

Java:Compile time and run time polymorphism

void sum(int a, int b){};
void sum(float a, float b){};

The above code is an example for compile time polymorphism but If user is entering the value of a and b, then method call will be determeined at compile time or run time ?

It will be determined at compile-time !!!

The method to be invoked will be determined depending on the reference type of the variables and not the actual value.

Your example would be determined at compile time . Example of runtime polymorphism.

Class A{
   void sum(int a, int b){};
}

Class B extends A{
   @Override
   void sum(int a, int b){};
}

Class C{
  A b = new B();
  b.sum(1, 2);  //whose sum() would be called (A/B)? Decision will take at run time. Runtime polymorphism.
}

Not very clear for your situation but when user has to enter value then too the code will decide which one to call.

public class Sample
{

    void sum(int a, int b)
    {
        System.out.print(a+b);
    }
    void sum(float a, float b){System.out.print(a+b);}
    public static void main(String[] a)
    {
        int a,b;
        float c,d;
        // logic for setting abcd;
        sum(a,b) //sum with int args will be called
        sum(c,d) //sum with float will be called
    }
}

And this will be resolved at compile time only. Hope this will help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM