SCJP : Inner Classes
Mock questions for this chapter: at bottom of this page
Creating Inner Classes Instances
Non-static inner classes have a hidden reference to the enclosing class instance. This means you must have an
instance of the enclosing class to create the inner class. You also have to use a special "new"
function that correctly initializes the hidden reference to the enclosing class. The special
"new" function is a member of the enclosing class.
public class InnerClassTest {
public class ReallyInner {
}
}
InnerClassTest o = new InnerClassTest();
InnerClassTest.ReallyInner i = o.new ReallyInner();
or
InnerClassTest.ReallyInner i = new InnerClassTest().new ReallyInner();
Example:
public class InnerClassTest {
public void foo() {
System.out.println("Outer class");
}
public class ReallyInner {
public void foo() {
System.out.println("Inner class");
}
public void test() {
this.foo();
InnerClassTest.this.foo();
}
}
public static void main(String[] args) {
InnerClassTest.ReallyInner i = new InnerClassTest().new ReallyInner();
i.test();
}
}
Output:
Inner class
Outer class
SCJP 1.5 SCJP 1.6 Inner classes Mock Exam Practice Questions
Questions no -1
What is the output for the below code ?
public class Outer {
private int a = 7;
class Inner {
public void displayValue() {
System.out.println("Value of a is " + a);
}
}
}
public class Test {
public static void main(String... args) throws Exception {
Outer mo = new Outer();
Outer.Inner inner = mo.new Inner();
inner.displayValue();
}
}
options
A)Value of a is 7
B)Compile Error - not able to access private member.
C)Runtime Exception
D)Value of a is 8
Correct answer is : A
Explanations : An inner class instance can never stand alone without a direct relationship to an instance of the outer class.
you can access the inner class is through a live instance of the outer class.
Inner class can access private member of the outer class.
Questions no -2
What is the output for the below code ?
public class Tech {
public void tech() {
System.out.println("Tech");
}
}
public class Atech {
Tech a = new Tech() {
public void tech() {
System.out.println("anonymous tech");
}
};
public void dothis() {
a.tech();
}
public static void main(String... args){
Atech atech = new Atech();
atech.dothis();
}
options
A)anonymous tech
B)Compile Error
C)Tech
D)anonymous tech Tech
Correct answer is : A
Explanations : This is anonymous subclass of the specified class type.
Anonymous inner class ( anonymous subclass ) overriden the Tech super class of tech() method.
Therefore Subclass method will get called.
|