SCJP : 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.
Questions no -3
What is the output for the below code ?
public class Outer {
private String x = "Outer variable";
void doStuff() {
String z = "local variable";
class Inner {
public void seeOuter() {
System.out.println("Outer x is " + x);
System.out.println("Local variable z is " + z);
}
}
}
}
options
A)Outer x is Outer variable.
B)Compile Error
C)Local variable z is local variable.
D)Outer x is Outer variable Local variable z is local variable
Correct answer is : B
Explanations : Cannot refer to a non-final variable z inside an inner class defined in a different method.
|