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


Download 1.52 Mb.
Pdf ko'rish
bet28/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   24   25   26   27   28   29   30   31   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

069.
070.
a.
b.
c.
071.
Explain what happens when the following code is
compiled.
class Electronics {
Electronics() {
}
public void displayPrice() {
Electronics();
}
}
Answer:
On compiling the above code, it causes a compilation error The
method Electronics() is undefined for the type
Electronics. This is because it is illegal to call a constructor
like this.
What are the possible access specifiers for a
constructor?
Answer:
Below are the possible access modifiers for a constructor–
private: This denotes that the constructor is accessible only
from its class
public: This denotes that the constructor is accessible from
any class which resides in any package
protected: This denotes that the constructor is accessible
from any class which resides in the same package
What will be the output of the following code snippet?
public class MyClass {


072.
public void callMe(int a) {
System.out.println(“Call me with int argument”);
}
public void callMe(long a) {
System.out.println(“Call me with long argument”);
}
public static void main(String args[]) {
MyClass myClassObj = new MyClass();
int i = 6;
myClassObj.callMe(i);
}
}
Answer:
The above code will print the following output:
Call me with int argument
Since the method callMe() is invoked with an integer value, the
method that accepts an integer argument gets invoked. If we
change the datatype of i to long, then the method that accepts
a long type of argument gets invoked.
How will you define a constructor? Give an example.
Answer:
Constructor is a special method which has the same name as the
class name but with no return type. The constructor is invoked
automatically whenever a new object is created. It is most
commonly used to execute some code that needs to be run as
soon as an object of a class is created like setting initial values to
the instance variables. The following code demonstrates this:



Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   24   25   26   27   28   29   30   31   ...   171




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