0

I am unable to create an inner class object in java:

package OOO;

class Car{
    class Engine{

        void display() {
            System.out.println("this is inner diaplay() method");
        }

    }
}

public class Sample8InnerClassCar {
    Car c = new Car();
    Car.Engine e = c.new Car.Engine();
}

its throwing me an error : cannot allocate member type Car.Engine. could someone please help me to understand more?

4
  • See also: stackoverflow.com/questions/70324/… Commented Aug 27, 2017 at 10:39
  • 2
    Try c.new Engine();. Using c already opens its scope. Commented Aug 27, 2017 at 10:42
  • also you can use "static" keyword for inner class Commented Aug 27, 2017 at 10:57
  • @DmitryGorkovets No you can't. 'Static inner' is a contradiction in terms'. If you make it 'static', it ceases to be 'inner', and the semantics change. Commented Aug 28, 2017 at 2:01

1 Answer 1

7

The correct syntax is:

Car.Engine e = c.new Engine();

Complete code snippet:

package OOO;

class Car {
    class Engine {

        void display() {
            System.out.println("this is inner diaplay() method");
        }
    }
}

public class Sample8InnerClassCar {

    Car c = new Car();
    Car.Engine e = c.new Engine();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Car.Engine e = new Car().new Engine(); also worked :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.