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.