Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to import nested types from class

Tags:

java

I can't figure out why this doesn't work. My top-level classes are in unnamed packages (for now; I'm planning on setting up packages later).

Iclass1.java:

public class Iclass1 {    
    public static class Nested1 {
        // whatever
    }    
}

Iclass2.java:

import Iclass1.*;
public class Iclass2 {
    private Nested1 someMember;
    // etc.
}

After I compile Iclass1.java with no errors, the compiler complains when I compile Iclass2.java: "error: package Iclass1 does not exist".

But the JLS says: (7.5.2)

import PackageOrTypeName . * ;

The PackageOrTypeName must be the canonical name (§6.7) of a package, a class type, an interface type, an enum type, or an annotation type.

and: (6.7)

The fully qualified name of a top level class or top level interface that is declared in an unnamed package is the simple name of the class or interface.

For every primitive type, named package, top level class, and top level interface, the canonical name is the same as the fully qualified name.

So it seems like Iclass1 is the canonical name of the type I'm trying to use in the import. What am I doing wrong?

(P.S. I now think import static would have been better, but it doesn't work either.)

like image 315
ajb Avatar asked Aug 05 '13 22:08

ajb


1 Answers

Since you have no packages, don't use import.

Because JLS §7.5 tells you not to:

A type in an unnamed package (§7.4.2) has no canonical name, so the requirement for a canonical name in every kind of import declaration implies that (a) types in an unnamed package cannot be imported, and (b) static members of types in an unnamed package cannot be imported. As such, §7.5.1, §7.5.2, §7.5.3, and §7.5.4 all require a compile-time error on any attempt to import a type (or static member thereof) in an unnamed package.

like image 70
Sajal Dutta Avatar answered Sep 21 '22 22:09

Sajal Dutta