Reputation: 861
Does this code here use static dispatch or dynamic dispatch?
public class Survey
{
public void DoSurvey()
{
System.out.println("DoSurvey is called");
}
}
Survey survey = new Survey();
survey.DoSurvey();
Because Java uses dynamic dispatch for all methods except private, final and static, the method to be called is still decided at runtime, which means the object that is assigned to the reference survey is examined at runtime and the correct method is called. Still, early binding is used which means that the compiler has the type of the reference survey and can check whether it is even legal to call the function. Then the function is dynamically dispatched at runtime when the nature of the underlying object is checked. Is my understanding right? Also what is an example where static dispatch is used?
Upvotes: 0
Views: 3048
Reputation: 13205
This ugly code (static methods are called via variables) displays some static-ish dispatch:
public class Parent {
public static void statictest(){System.out.println("Parent.statictest");}
public void test(){System.out.println("Parent.test");}
}
public class Child extends Parent {
public static void statictest(){System.out.println("Child.statictest");}
public void test(){System.out.println("Child.test");}
}
public static void main(String[] args) {
Child c=new Child();
Parent p=c;
c.test();
p.test();
c.statictest();
p.statictest();
}
will result in
Child.test
Child.test
Child.statictest
Parent.statictest
However I would not dare claim "that is static dispatch, period", since I have not thought over what would happen in case of overloading, especially when signatures solely differ in argument types which are related to each other (so one inherits from another).
Upvotes: 2