Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a nested type as a generic type argument in the enclosing class' supertype declaration

I basically have a question about why the following does not work. I have an abstract class:

public abstract class Abstrct <T> {

}

I then define a class that makes use of that class with a public inner class defined that I want to use for the generic parameter, as follows:

public class Outer extends Abstrct<Inner> {
    public class Inner {

    }
}

As I am learning Java still, I am more interested in why it does not work. Not so much as to how to make it work, but I would be interested in that also.

like image 435
user1524133 Avatar asked May 28 '15 15:05

user1524133


People also ask

Which types can be used as arguments of a generic type?

The actual type arguments of a generic type are. reference types, wildcards, or. parameterized types (i.e. instantiations of other generic types).

Can Java inner class be generic?

If I have one class (Class1) which takes the type E and also has an internal class (Class2) which I also want to take type E which should be the same as the E of Class1 in all cases. Class2 is a private internal class, so it will only ever be used by instances of Class1; which means it will never ever have any other E.

What is type arguments in Java?

A type parameter, also known as a type variable, is an identifier that specifies a generic type name. The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.


2 Answers

Inner is not in scope for the class declaration of Outer. It's not a known type name when used in the extends clause. Use a qualified reference:

class Outer extends Abstract<Outer.Inner>

Or import it:

import com.example.Outer.Inner;

From the specification, regarding Scope:

The scope of a declaration of a member m declared in or inherited by a class type C (§8.1.6) is the entire body of C, including any nested type declarations.

The extends clause is part of the class' Superclass declaration, as described in the Specification. It's not part of the class body.

The scope of a type used in an import statement, however,

[..] is all the class and interface type declarations (§7.6) in the compilation unit in which the import declaration appears, as well as any annotations on the package declaration (if any) of the compilation unit .

like image 118
Sotirios Delimanolis Avatar answered Sep 17 '22 19:09

Sotirios Delimanolis


You can use Abstrct<Outer.Inner> making the type unambiguous and valid.

like image 45
m4ktub Avatar answered Sep 21 '22 19:09

m4ktub