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


Explain what happens when the following code is


Download 1.52 Mb.
Pdf ko'rish
bet8/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   4   5   6   7   8   9   10   11   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

Explain what happens when the following code is
compiled and state whether it uses method overloading or
overriding.
class Electronics {
public void displayPrice (Float price) {} //Line 1
}
class Camera extends Electronics {


008.
009.
public void displayPrice (String price) {} //Line 2
}
Answer:
The above compiles fine. It uses method overloading. Camera is
a sub–class of Electronics and both classes have a method
called displayPrice. However, the displayPrice method in
both classes differ in the type of argument.
Write a Java code sample that demonstrates method
overloading.
Answer:
Method overloading occurs when there are two or more methods
in a class with the same name but with a different number/type of
arguments.The following code demonstrates this:
class Laptop {
public void displayPixel (int width, int height) { };
//Line 1
public void displayPixel (float width, float height)
{}; //Line 2
}
The class Laptop has two method with the name as
displayPixel. The displayPixel method at Line 1 has two
arguments, both of type int. The displayPixel method at Line
2, displayPixel method has two arguments both of type float.
So here, the displayPixel method is said to be overloaded.
What is polymorphism? How does Java support
Polymorphism?


010.
Answer:
Polymorphism literally means “many forms”. It is the ability to use
the same interface to execute different code. Java achieves
polymorphism via method overloading and method overriding.
Method overloading occurs when there are many methods in a
class with the same name but different number/type of
arguments. The version of an overloaded method that will be
invoked is determined at compile time based on the number/type
of arguments passed in. Method overriding occurs when a sub–
class has a method with the same name and type signature as a
method in the super class. The version of an overridden method
that will be invoked is determined at run time based on the type
of object that invokes the method.

Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   4   5   6   7   8   9   10   11   ...   171




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