fork download
  1.  
  2. /* Name of the class has to be "Main" only if the class is public. */
  3. public class Main
  4. {
  5. public static class MyClass {
  6. public MyClass() {
  7. System.out.println("MyClass default constructor");
  8. }
  9. }
  10.  
  11. public static class MySubClass extends MyClass {
  12. public MySubClass() {
  13. super();
  14. System.out.println("MySubClass default constructor");
  15. }
  16. }
  17.  
  18. public static class Factory<T extends MyClass> {
  19. public T create() {
  20. final T t = new T();
  21. return t;
  22. }
  23.  
  24. public T create(final Class<? extends T> clazz) throws Exception {
  25. final T t = clazz.newInstance();
  26. return t;
  27. }
  28. }
  29.  
  30. public static void main(String[] args) throws Exception {
  31. final Factory<MySubClass> factory = new Factory<MySubClass>();
  32.  
  33. final MySubClass msc = factory.create();
  34. // final MySubClass msc = factory.create(MySubClass.class);
  35.  
  36. System.out.println("Created instance: " + msc);
  37. }
  38. }
Compilation error #stdin compilation error #stdout 0.12s 320576KB
stdin
Standard input is empty
compilation info
Main.java:20: error: unexpected type
			final T t = new T();
			                ^
  required: class
  found:    type parameter T
  where T is a type-variable:
    T extends MyClass declared in class Factory
1 error
stdout
Standard output is empty