1

i've got a Problem with java and generic classes.
Given the following code

public class A {
    public void n() { 
        System.out.println("In A"); 
    }
}

public class B extends A {
    @Override
    public void n() {
        System.out.println("In B");
        super.n();
    }
}

public class C {
    public A m_a;
    public <T extends A> C( Class<T> a ) {
        try {
            m_a = a.newInstance();
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
    public void print(){ m_a.n(); };
}

i try to instantiate an Object of Class C as following

C c = new C( B.class );

but get the following error:

java.lang.InstantiationException: testdbvsfile.Main$B
    at java.lang.Class.newInstance(Unknown Source)
    at testdbvsfile.Main$C.<init>(Main.java:63)
    at testdbvsfile.Main.main(Main.java:76)
Caused by: java.lang.NoSuchMethodException: testdbvsfile.Main$B.<init>()
    at java.lang.Class.getConstructor0(Unknown Source)<br>
    ... 3 more

How can i make it work?
Thanks for help.

btw: I'm using jre1.8.0_65

Krustenkaese
  • 155
  • 1
  • 9

1 Answers1

5

The problem is that you are using non-static inner classes. This is evident from the stack trace, where Main$B is given for the name of your B class, which lacks static in its declaration.

Constructors of non-static member classes take an implicit parameter with the instance of their enclosing class.

Making your inner classes static will fix this problem. You could also fix the problem by moving your A, B, and C classes out of the Main class.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523