Inner class Questions with Answers

11 practice questions on Inner class (Core Java) with answers and step-by-step solutions. Try 10 samples below, then practise all 11 free in the AptiNest app.

Sample questions

Question 1Medium

Which is true about an anonymous inner class?

  1. It can extend exactly one class and implement exactly one interface.
  2. It can extend exactly one class and can implement multiple interfaces.
  3. It can extend exactly one class or implement exactly one interface.
  4. It can implement multiple interfaces regardless of whether it also extends a class.

Answer: C. It can extend exactly one class or implement exactly one interface.

Explanation

Option C is correct because the syntax of an anonymous inner class allows for only one named type after the new, and that type must be either a single interface (in which case the anonymous class implements that one interface) or a single class (in which case the anonymous class extends that one class).

Option A, B, D, and E are all incorrect because they don't follow the syntax rules described in the response for answer Option C.

Step-by-step solution

  1. An anonymous inner class is written with new followed by one type name.
  2. That one type is either a single class, which it extends, or a single interface, which it implements.
  3. It cannot extend a class and implement an interface together, and it cannot implement several interfaces.
  4. The correct answer is option C.

Why the other options are wrong

  • A. It cannot both extend one class and implement one interface in the same declaration.
  • B. It cannot implement multiple interfaces, since only one named type is allowed after new.
  • D. It cannot implement multiple interfaces, since only one named type is allowed after new.

Tip: An anonymous class gets one class or one interface after new, never both.

Question 2Medium

3. What will be the output of the program?

public class TestObj
{
    public static void main (String [] args)
    {
        Object o = new Object() /* Line 5 */
        {
            public boolean equals(Object obj)
            {
                return true;
            }
        }      /* Line 11 */

        System.out.println(o.equals("Fred"));
    }
}
  1. It prints "true".
  2. It prints "Fred".
  3. An exception occurs at runtime.
  4. Compilation fails

Answer: D. Compilation fails

Explanation

This code would be legal if line 11 ended with a semicolon. Remember that line 5 is a statement that doesn't end until line 11, and a statement needs a closing semicolon! View Answer Workspace Report Discuss in Forum

Step-by-step solution

  1. The anonymous class expression starts with new Object() and a body.
  2. A statement that assigns it must end with a semicolon after the closing brace.
  3. Line 11 has no semicolon, so the code does not compile.
  4. So option D is correct, which is Compilation fails.

Why the other options are wrong

  • A. The code never runs, so nothing prints.
  • B. Equals returns a boolean, and the code never runs.
  • C. The error happens at compile time, not at runtime.

Tip: End a statement that assigns an anonymous class with a semicolon.

Question 3Medium

What will be the output of the program?

public abstract class AbstractTest
{
    public int getNum()
    {
        return 45;
    }
    public abstract class Bar
    {
        public int getNum()
        {
            return 38;
        }
    }
    public static void main (String [] args)
    {
        AbstractTest t = new AbstractTest()
        {
            public int getNum()
            {
                return 22;
            }
        };
        AbstractTest.Bar f = t.new Bar()
        {
            public int getNum()
            {
                return 57;
            }
        };

        System.out.println(f.getNum() + " " + t.getNum());
    }
}
  1. 57 22
  2. 45 38
  3. 45 57
  4. An exception occurs at runtime.

Answer: A. 57 22

Explanation

You can define an inner class as abstract, which means you can instantiate only concrete subclasses of the abstract inner class. The object referenced by the variable t is an instance of an anonymous subclass of AbstractTest, and the anonymous class overrides the getNum() method to return 22. The variable referenced by f is an instance of an anonymous subclass of Bar, and the anonymous Bar subclass also overrides the getNum() method (to return 57). Remember that to instantiate a Bar instance, we need an instance of the enclosing AbstractTest class to tie to the new Bar inner class instance. AbstractTest can't be instantiated because it's abstract, so we created an anonymous subclass (non-abstract) and then used the instance of that anonymous subclass to tie to the new Bar subclass instance.

Step-by-step solution

  1. T is an anonymous subclass of AbstractTest, and its getNum() returns 22.
  2. F is an anonymous subclass of Bar, created with t.new Bar(), and its getNum() returns 57.
  3. The println prints f.getNum() then t.getNum(), separated by a space: 57 22.
  4. That is option A, which is the correct answer.

Why the other options are wrong

  • B. 45 is the base AbstractTest method, but t overrides it to return 22, and f's Bar subclass returns 57.
  • C. 45 is the base value, but t and f both override getNum(), so 57 and 22 are printed.
  • D. No exception happens: t.new Bar() is valid because t is an instance of the enclosing class.

Tip: An anonymous subclass overrides the method it defines; to create an inner class object, you need an instance of its outer class.

Question 4Medium

which statement, inserted at line 10, creates an instance of Bar?

class Foo
{
    class Bar{ }
}
class Test
{
    public static void main (String [] args)
    {
        Foo f = new Foo();
        /* Line 10: Missing statement ? */
    }
}
  1. Foo.Bar b = new Foo.Bar();
  2. Foo.Bar b = f.new Bar();
  3. Bar b = new f.Bar();
  4. Bar b = f.new Bar();

Answer: B.

Explanation

class) in the reference declaration, then using a reference to the enclosing class to invoke new on the inner class.
Option A, C and D all use incorrect syntax. A is incorrect because it doesn't use a reference to the enclosing class, and also because it includes both names in the new.C is incorrect because it doesn't use the enclosing class name in the reference variable declaration, and because the new syntax is wrong.D is incorrect because it doesn't use the enclosing class name in the reference variable declaration.
View Answer Workspace Report Discuss in Forum

Step-by-step solution

  1. Inner class Bar must be accessed via Foo's reference f.
  2. Use f.new Bar() to create instance of inner class Bar.
  3. Reference variable must be declared as Foo.Bar type.
  4. Correct syntax is ```java Foo.Bar b = f.new Bar(); ```
  5. This matches option B exactly.
  6. Final answer: ```java Foo.Bar b = f.new Bar(); ```

Why the other options are wrong

  • A. An inner class needs an enclosing Foo object, so new Foo.Bar() does not compile here.
  • C. f.Bar is not valid syntax for creating an inner class; the form is f.new Bar().
  • D. Bar is not in scope in Test without the Foo qualifier, so the declaration will not compile.

Tip: Use outer class reference with new when creating inner class instances.

Question 5Medium

Which is true about a method-local inner class?

  1. It must be marked final.
  2. It can be marked abstract.
  3. It can be marked public.
  4. It can be marked static.

Answer: B. It can be marked abstract.

Explanation

Option B is correct because a method-local inner class can be abstract, although it means a subclass of the inner class must be created if the abstract class is to be used (so an abstract method-local inner class is probably not useful).
Option A is incorrect because a method-local inner class does not have to be declared final (although it is legal to do so).
C and D are incorrect because a method-local inner class cannot be made public (remember-you cannot mark any local variables as public), or static.

Step-by-step solution

  1. A method-local inner class can be marked abstract or final.
  2. It cannot be public or static, and it need not be final.
  3. So option B is correct.

Why the other options are wrong

  • A. It does not have to be final.
  • C. Access modifiers like public are not allowed for local classes.
  • D. It cannot be static.

Tip: Local classes can be abstract or final only.

Question 6Medium

Which statement is true about a static nested class?

  1. You must have a reference to an instance of the enclosing class in order to instantiate it.
  2. It does not have access to nonstatic members of the enclosing class.
  3. It's variables and methods must be static.
  4. It must extend the enclosing class.

Answer: B. It does not have access to nonstatic members of the enclosing class.

Explanation

Option B is correct because a static nested class is not tied to an instance of the enclosing class, and thus can't access the nonstatic members of the class (just as a static method can't access nonstatic members of a class).
Option A is incorrect because static nested classes do not need (and can't use) a reference to an instance of the enclosing class.
Option C is incorrect because static nested classes can declare and define nonstatic members.
Option D is wrong because it just is. There's no rule that says an inner or nested class has to extend anything.

Step-by-step solution

  1. A static nested class belongs to the outer class, not to an outer instance.
  2. So it has no outer object and cannot use non-static members of the enclosing class.
  3. It does not need an outer object, and it does not have to extend anything.
  4. The correct answer is option B.

Why the other options are wrong

  • A. A static nested class needs no outer instance to be created.
  • C. A static nested class can have non-static variables and methods, so this is not required.
  • D. Nested classes do not have to extend the enclosing class.

Tip: Static nested classes need no outer object and cannot touch the outer class's instance members.

Question 7Medium

What will be the output of the program?

public class HorseTest
{
    public static void main (String [] args)
    {
        class Horse
        {
            public String name; /* Line 7 */
            public Horse(String s)
            {
                name = s;
            }
        } /* class Horse ends */

        Object obj = new Horse("Zippo"); /* Line 13 */
        Horse h = (Horse) obj; /* Line 14 */
        System.out.println(h.name);
    }
} /* class HorseTest ends */
  1. An exception occurs at runtime at line 10.
  2. It prints "Zippo".
  3. Compilation fails because of an error on line 7.
  4. Compilation fails because of an error on line 13.

Answer: B. It prints "Zippo".

Explanation

The code in the HorseTest class is perfectly legal. Line 13 creates an instance of the method-local inner class Horse, using a reference variable declared as type Object. Line 14 casts the Horse object to a Horse reference variable, which allows line 15 to compile. If line 14 were removed, the HorseTest code would not compile, because class Object does not have a name variable.

Step-by-step solution

  1. Horse is a local class inside main; its constructor sets name to Zippo.
  2. Line 13 creates a Horse object and stores it in an Object variable, which is legal.
  3. Line 14 casts obj back to Horse, so h.name can be used.
  4. Line 15 prints h.name, which is Zippo, so option B is the correct answer.

Why the other options are wrong

  • A. No exception happens, because the cast is valid: obj really holds a Horse.
  • C. The code compiles: name is a public field of the local class Horse.
  • D. Line 13 compiles, since an Object variable can hold a Horse reference.

Tip: A cast to the real object's class is safe; casting to a class the object is not will throw ClassCastException.

Question 8Medium

What will be the output of the program?

public class Foo
{
    Foo()
    {
        System.out.print("foo");
    }

class Bar
{
    Bar()
    {
        System.out.print("bar");
    }
    public void go()
    {
        System.out.print("hi");
    }
} /* class Bar ends */

    public static void main (String [] args)
    {
        Foo f = new Foo();
        f.makeBar();
    }
    void makeBar()
    {
        (new Bar() {}).go();
    }
}/* class Foo ends */
  1. Compilation fails.
  2. An error occurs at runtime.
  3. It prints "foobarhi"
  4. It prints "barhi"

Answer: C. It prints "foobarhi"

Explanation

Option C is correct because first the Foo instance is created, which means the Foo constructor runs and prints "foo". Next, the makeBar() method is invoked which creates a Bar, which means the Bar constructor runs and prints "bar", and finally the go() method is invoked on the new Bar instance, which means the go() method prints "hi".

Step-by-step solution

  1. New Foo() runs the Foo constructor, which prints foo.
  2. makeBar() creates an anonymous subclass of Bar, which runs the Bar constructor and prints bar.
  3. go() is called on that object and prints hi.
  4. The output is foobarhi, which is option C.

Why the other options are wrong

  • A. The code compiles: Bar is an inner class and is created inside an instance method of Foo.
  • B. No runtime error occurs, because every call is valid.
  • D. The Foo constructor also prints foo first, so the output is missing foo.

Tip: Creating an object runs its constructor, and an anonymous subclass also runs the superclass constructor first.

Question 9Medium

Which constructs an anonymous inner class instance?

  1. Runnable r = new Runnable() { };
  2. Runnable r = new Runnable(public void run() { });
  3. Runnable r = new Runnable { public void run(){}};
  4. System.out.println(new Runnable() {public void run() { }});

Answer: D.

Explanation

D is correct. It defines an anonymous inner class instance, which also means it creates an instance of that new anonymous class at the same time. The anonymous class is an implementer of the Runnable interface, so it must override the run() method of Runnable.
A is incorrect because it doesn't override the run() method, so it violates the rules of interface implementation.
B and C use incorrect syntax.

Step-by-step solution

  1. An anonymous inner class is written inline as new Interface() { body } and must implement every abstract method.
  2. Option A has an empty body, so run() is missing and the class does not compile.
  3. Options B and C are syntax errors: a method cannot sit inside the constructor call, and new Runnable needs parentheses.
  4. Option D creates the anonymous class with run() implemented and passes it to println, so it is valid. Answer: option D.

Why the other options are wrong

  • A. The empty body does not implement run(), so the anonymous class is incomplete and will not compile.
  • B. A method declaration inside the parentheses of new Runnable(...) is invalid syntax.
  • C. New Runnable { ... } is missing the parentheses, which is invalid syntax.

Tip: An anonymous class is valid only when it fills in every abstract method, written as new Type() { body }.

Question 10Medium

which statement, if placed in a class other than MyOuter or MyInner, instantiates an instance of the nested class?

public class MyOuter
{
    public static class MyInner
    {
        public static void foo() { }
    }
}
  1. MyOuter.MyInner m = new MyOuter.MyInner();
  2. MyOuter.MyInner mi = new MyInner();
  3. MyOuter m = new MyOuter();
  4. MyInner mi = new MyOuter.MyInner();

Answer: A.

Explanation

A static nested class is created with its full name, MyOuter.MyInner. Option B uses only MyInner in new, which is not in scope outside MyOuter. Option C creates MyOuter, and option D uses the short name MyInner for the variable type, which is not in scope either.

Step-by-step solution

  1. MyInner is static and nested in MyOuter, so its full name is MyOuter.MyInner.
  2. A class outside both can create it with new MyOuter.MyInner().
  3. Options B and D use the short name MyInner in the declaration or creation, which is not visible here.
  4. Option C creates a MyOuter object, not a MyInner object, so the correct answer is option A.

Why the other options are wrong

  • B. The short name MyInner is not in scope outside MyOuter.
  • C. This creates a MyOuter object, not a MyInner object.
  • D. The variable type MyInner needs the full name MyOuter.MyInner outside MyOuter.

Tip: A static nested class is created as Outer.Inner with new Outer.Inner().

Practise all 11 questions free

The full question bank with timed practice, progress tracking and Vidya, your AI tutor. Free, no ads.

Open this topic in the app →

Related topics

See all Core Java topics · All topics