Himanshu
Himanshu

Reputation: 53

How to know whether it is a compile-time polymorphism or run-time polymorphism?

Consider a superclass:

class superclass
{
    public void fun() {.....}
}

and it's subclass:

class subclass extends superclass
{
    public void fun(){.......}
    public static void main()
    {
         superclass sup1=new superclass(); 
         sup1.fun()//statement 1
         superclass sup2=new subclass();
         sup2.fun() //statement 2
         subclass sub1=new subclass(); 
         sub1.fun()//statement 3
     }
}

I follow following way to determine whether it's a compile time polymorphism or run time polymorphism for statements 1,2 and 3:

Question 1: I want to know whether this approach is right or wrong?

Question 2: And what will be the procedure when instead of a reference variable a function call statement is used which returns the adress of the object? I think that the return type of the function which returns the adress will be used in determining the type of polymorphism. Am i correct?

Upvotes: 0

Views: 274

Answers (2)

Vishal choudhary
Vishal choudhary

Reputation: 315

i think all statement are run time polymorphism in java every non static method bind at run time. object take reference at run so there is no existance of any object at compile time so alwayes when you call any method with the help of object that will be run time binding. here in your code function is called by object this all statement are run time polymorphism and one another thing is function overriding will always be runtime polymorphism becouse the reference will be assing to the object at run time but function overloading might be both at run time or at compile time when you overlaod a non static function that will gona bind at run time or when you overlaod a static memeber only that function will bind at compile time

Upvotes: 0

jokster
jokster

Reputation: 577

In Java, you always have runtime polymorphism for any overridable method! The compiler can't know all possible derivations of a class, so it can't follow your algorithm above.

AFAIK, the logic goes like this:

  1. At compile time, the compiler determines the correct signature using the type of the variable.
  2. At run time, the jvm determines the correct method using the type of the actual object and the signature determined at compile time.

Upvotes: 1

Related Questions