Create inner classes including static inner class, local class, nested class, and anonymous inner class.
1. The correct answer is C.
There's nothing wrong with the
ITest interface; you can declare inner interfaces without problems. What is wrong is that the declaration of the anonymous class is missing the closing semicolon.
Remember, the declaration of an anonymous class is a Java expression, like declaring an
int variable, so it has to end with a semicolon after the curly brace.
2. The correct answer is B.
Local classes (the ones defined inside a method) and anonymous classes (the ones defined without a name) can only access variables of the enclosing context that are final or effectively final (which means that a variable cannot be modified after its initialization).
i is modified after the method call so that it won't qualify as an effectively final variable. However, this is not the variable used inside
method(), since in Java, all parameters are passed by value. As the parameter is not modified inside the method, it is effectively final and can be used inside local class
3. The correct answer is B.
main defines an anonymous class that is a subclass of type
Question_3_3 doesn't define any methods, nothing is overridden and, although the method sum is defined inside the anonymous class, no methods apart from the ones inherited from
Object can be called.
4. The correct answer is D.
There's nothing wrong with the static inner class declaration or the way it is instantiated. Since all happens in the same class, the
main method can access the private members of the inner class, so there's no problem with that neither.
5. The correct answer is A.
This program first fails on the line marked as
// 1 because when instantiating an inner class from outside its enclosing class, you don't use its compound name (in this case
A.B) on the right side of the statement. So instead of:
A.B b = a.new A.B();
A.B b = a.new B();
If you want to call method
go(), the correct code is:
A a = new A();
A.B bb = a.new B();
A.B.C cc = bb.new C();
6. The correct answer is B.
The inner class
A can be marked as
private and method
main can access it because both are members of
main is a
static method, nothing guarantees that there will be an instance of
Question_3_6, so you must explicitly create one to instantiate the inner class
A. So instead of:
Question_3_6.A a = new A();
You have to use:
Question_3_6 q = new Question_3_6();
Question_3_6.A a = q.new A();
7. The correct answer is C.
Local classes cannot have access modifiers. The only allowed modifiers are
8. The correct answer is B.
add of the anonymous class returned by method create uses the effectively final (as it's never modified) parameter
i, not the instance variable of the same name.
Since all the code is valid,
12 is printed.