Joker
Joker

Reputation: 11156

InstantiationException on Inner Class

I am getting java.lang.InstantiationException after running this program, however i was expecting a Hello World as a output.

public class Test {
        public static void main(String[] args) throws Exception {
            new Test().greetWorld();
        }

        private void greetWorld() throws Exception {
            System.out.println(Test2.class.newInstance());
        }

         class Test2 {
            public String toString() {
                return "Hello world";
            }
        }
    }

Can some one tell me about this exception and why it is not printing Hello World

Upvotes: 2

Views: 222

Answers (1)

Sweeper
Sweeper

Reputation: 271595

This is because Test2 is not a static class. Make it static to make this work.

static class Test2 {
    public String toString() {
        return "Hello world";
    }
}

Alternatively, move Test2 out of Test1.

Think about how you would normally create an instance of Test2. Since it is not static, you can't just do

Test1.Test2 obj = new Test1.Test2();

You need to be in a non-static context of Test1.

That is why you can't directly get the constructor from the Class object.

Upvotes: 2

Related Questions