Core java interview Questions You'll Most Likely Be Asked (Second Edition)


Download 1.52 Mb.
Pdf ko'rish
bet37/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   33   34   35   36   37   38   39   40   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

095.
Answer:
This code prints the following output:
I’m a shape!
I’m a Circle!
I’m a Triangle!
Here, Shape is a base class with Circle and Triangle sub–
classes. There is a printShape method in the base class that is
overridden in both the sub–classes. When a method is
overridden, the type of object assigned and not the reference
variable determines which version of the overridden method gets
invoked. At Line 1, a variable of type Shape is assigned a Shape
object, so the printShape method in the Shape class is
invoked. At Line 2, a variable of type Shape is assigned a
Circle object, so the printShape method in the Circle class
is invoked. At Line 3, a variable of type Shape is assigned a
Triangle object, so the printShape method in the Triangle
class is invoked. This feature of Java is known as runtime
polymorphism.
Explain what is the issue with the following code snippet:
public class Base {
public void doSomething() {
}
}
public class Sub extends Base{
public void doSomethingElse() {
}
}
public class Demo {


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.

Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   33   34   35   36   37   38   39   40   ...   171




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling