Reputation: 53
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:
compiler first determine the class type of the reference variable used in calling statement, compiler then check whether there is any derived class of this base present in the source code or not and whether if method used in calling statement is overriden or not in the derived class. If a derived class is found and it contains overriden version of the function, then at run time the type of object to which reference variable is referencing is determined and that class' type function is executed(run time polymorphism) otherwise function present in the class (of which reference variable belongs to) is executed(compile time polymorphism).
going by this way: 1) statement 1 will cause run time polymorphism.
2)statement 2 will also cause run time polymorphism.
3)statement 3 will cause compile time polymorphism.
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
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
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:
Upvotes: 1