Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating instances of public inner classes of generic classes

So I have something like the following:

public class Enclosing<T extends Comparable<T>> {
    // non-relevant code snipped
    public class Inner {
        private T value;
        public Inner(T t) {
            value = t;
        }
    }
}

Everything compiles and the world is happy. However, whenever I try to create an instance of Enclosing.Inner as follows, I can't:

new Enclosing<Integer>.Inner(5);

The following error happens:

Cannot allocate the member type Enclosing<Integer>.Inner using a parameterized compound name; use its simple name and an enclosing instance of type Enclosing<Integer>.

It is important to note that I cannot make the inner class static, because it contains a field of type T.

How can I work around this?

like image 769
knpwrs Avatar asked Nov 22 '11 02:11

knpwrs


People also ask

How do you create an instance of an inner class?

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass outerObject = new OuterClass(); OuterClass. InnerClass innerObject = outerObject.

Can an inner class be public?

Java inner class can be declared private, public, protected, or with default access whereas an outer class can have only public or default access.

Can you create an inner class inside a method?

Method-local Inner Class In Java, we can write a class within a method and this will be a local type. Like local variables, the scope of the inner class is restricted within the method. A method-local inner class can be instantiated only within the method where the inner class is defined.

How do you create a generic class?

A Generic Version of the Box Class To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class.


1 Answers

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

  Enclosing<Integer> outerObject = new Enclosing<Integer>();
  Enclosing<Integer>.Inner innerObject = outerObject.new Inner();

The ugly syntax suggests a code smell in this design. There should probably be a factory method of some kind in the Enclosing class (getInner or something) and the inner class should probably implement a public interface if it is being used from outside its enclosing class.

like image 53
Thilo Avatar answered Sep 18 '22 00:09

Thilo