3

I have a class like:

 package com.example;

 public abstract class AbstractClass<S> {
       //stuffs
 }

Then a class that extends it, and define the generic type as its own inner class:

package com.example2;

import com.example.AbstractClass;
import com.example2.MyObject.MyObjectInnerClass;

public class MyObject extends AbstractClass<MyObjectInnerClass> {

     //other stuffs

     public static class MyObjectInnerClass {

     }
}

Why is needed the import of com.example2.MyObject.MyObjectInnerClass if it stays in the same file?

2 Answers 2

5
import com.example.AbstractClass;
import com.example2.MyObject.MyObjectInnerClass;

public class MyObject extends AbstractClass<MyObjectInnerClass> {

It is needed because the nested (not inner) class MyObjectInnerClass only exists with an unqualifed name inside the {, which comes after the use of it in the extendsclause.

A more conventional way of writing it would be:

import com.example.AbstractClass;

public class MyObject extends AbstractClass<MyObject .MyObjectInnerClass> {
Sign up to request clarification or add additional context in comments.

1 Comment

This should be the accepted answer, as it actually gives the reason why.
2

Let's start by saying - it's not an inner class, it's a nested class (inner class is a non-static nested class).

That import is needed for two important reasons:

  1. It needs to know which class do you mean - You could also have MyObjectInnerClass as a class in the same package as MyObject. Importless reference to such class would point to exactly that one.
  2. That's what nested classes are for - to group classes in a logical hierarchical structure.

Note that it is customary to, instead of import, write MyObject.MyObjectInnerClass to put emphasis on the relationship between the two.

3 Comments

(1) isn't correct at all: either the import or the qualification is required regardless of whether there is any ambiguity. (2) isn't a reason why the import is required.
@EJP (1) is correct - since we're talking about language specification the possibility of ambiguity is enough to make import neccessery, and that's what I wrote. As for (2)... True
It is not necessary. You can write the FQN. No ambiguity there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.