Reputation: 860
I have a following code
class OuterClass<T>{
class Innerclass{
int k;
}
public static void main(String argv[]){
OuterClass<Integer> out =new OuterClass<>();
Innerclass in; // errors out
}
}
But for a class with no generics like the following code, I could create object for inner class.
class OuterClass{
class Innerclass{
int k;
}
public static void main(String argv[]){
OuterClass out =new OuterClass();
Innerclass in; // No error
}
}
why am i not able to create object of inner class though no generics are used in the inner class in my first example? Please explain.
Upvotes: 2
Views: 100
Reputation: 20043
Your main
method belongs to OuterClass
and is static in there. Since InnerClass
is not a static class but implicitly depends on the generic type T
(the generic type is available in the inner class, even if your example isn't using it), you cannot reference it from a static method.
In other words, since InnerClass
depends on the generic type, you cannot break it "lose" from OuterClass
and use it outside of it.
If your inner class won't depend on the generic type, you can just make it static. However, you might want to consider just extracting it into a separate class rather than nesting classes in this case:
class OuterClass<T> {
static class InnerClass {
int k;
}
public static void main( String argv[] ) {
InnerClass inner = new InnerClass();
}
}
If the generic is important for the inner class, you can tell the compiler which generic to infer for the outer class by specifying it (note that the generic type of outer
and inner
must match) or by using OuterClass.InnerClass
in which case the compiler will use the raw type:
class OuterClass<T> {
class InnerClass {
int k;
}
public static void main( String argv[] ) {
OuterClass<String> outer = new OuterClass<String>();
// works and has the "correct" generic type
OuterClass<String>.InnerClass inner1 = outer.new InnerClass();
// works, but uses the raw type
OuterClass.InnerClass inner2 = outer.new InnerClass();
}
}
Note that you need an enclosing instance outer
of type OuterClass<T>
in order to instantiate InnerClass
(since the class is not static, it belongs to an instance of OuterClass
).
This also goes for the example without generics: you will need an enclosing instance to instantiate the inner class, so
class OuterClass {
class InnerClass {
int k;
}
public static void main( String argv[] ) {
OuterClass outer = new OuterClass();
InnerClass in = outer.new InnerClass();
}
}
will work while
class OuterClass {
class InnerClass {
int k;
}
public static void main( String argv[] ) {
OuterClass outer = new OuterClass();
InnerClass in = new InnerClass();
}
}
won't.
Upvotes: 2