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


Download 1.52 Mb.
Pdf ko'rish
bet32/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   28   29   30   31   32   33   34   35   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

Anonymous inner class: A class that has no name and can
be instantiated only once when it is defined is known as an
anonymous inner class. It does not have a constructor as it
does not have a name. It cannot be static. The class
definition ends with a semicolon.
Write a code sample that demonstrates how you can
instantiate an inner class from an outer class.
Answer:


082.
Suppose you has an outer class called TestOuter with an inner
class called TestInner. The following code snippet
demonstrates how you can instantiate the TestInner class:
TestOuter outer = new TestOuter();
TestOuter.TestInner inner = outer.new TestInner();
So first, you need to create an instance of the outer class. Since
the inner class is a member of the outer class, you can then
create an instance of the inner class by using the dot operator(.).
Also, while invoking the inner class constructor with the new
operator, you need to specify the outer class object instance with
the dot operator.
Write a code sample that demonstrates an Inner Class.
Answer:
The following code demonstrates an inner class:
class Outer {
private int iValue = 100;
public void callInner() {
Inner inner = new Inner();
inner.readValue();
}
class Inner {
public void readValue() {
System.out.println(“Value is: “ + iValue);
}
}
}


083.
In the above code, the class Outer has an inner class Inner.
The method callInner() instantiates the Inner class and
invokes its readValue method.
What is “method–local” inner class.
Answer:
A method–local inner class is an inner class which is defined
within a method of an enclosing class. It needs to be instantiated
within the method itself and cannot be instantiated outside the
method. It uses only final variables within the method. It can only
have abstract and final modifier. The following code
demonstrates a method local inner class:
public class Outer {
public void doSomething() {
final int i = 10;
class Inner{
void doSomethingInInner() {
System.out.println(i);
}
}
Inner inner = new Inner();
inner.doSomethingInInner();
}
}
This code specifies a class Outer with a method
doSomething(). There in a class Inner defined within this
method. Inner is a method local class. It is instantiated within
the method itself.



Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   28   29   30   31   32   33   34   35   ...   171




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