096.
097.
public static void main(String[] args) {
Base base = new Base(); //Line 1
base.doSomethingElse(); //Line 2
}
}
Answer:
This code causes a compilation error at Line 2. It defines a class
called Base and a sub–class called Sub. Line 1
creates a Base
class object. Line 2 invokes the base.doSomethingElse()
method. Since the doSomethingElse() method is defined in
Sub, Base does not have access to it and so a compilation error
occurs at Line 2.
Why is dynamic method dispatch?
Answer:
Dynamic method dispatch is the mechanism
by which the version
of an overridden method that will be invoked is determined at run
time. Java achieves run time polymorphism via dynamic method
dispatch. In Java, a super–class
reference variable can be
assigned an object of a sub–class. When an overridden method
is invoked via a super–class reference object,
the version of the
method to be invoked is determined based on the type of object
that is assigned to the superclass variable. So, if a sub–class
object is assigned to a super–class variable and an overridden
method
is invoked, then the method from the sub–class gets
executed. This mechanism allows different methods to be
executed using the same method call.
Do'stlaringiz bilan baham: