Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot `import static` static nested class?

I have a class A with a static nested class inside it called B:

import static A.B.*;

class A {
    static class B {
        static int x;
        static int y;
    }
    public static void main(String[] args) {
        System.out.println(x);
    }
}

I want to static import everything in B, but it wont work:

$ javac A.java
A.java:1: package A does not exist
import static A.B.*;
               ^
A.java:9: cannot find symbol
symbol  : variable x
location: class A
        System.out.println(x);
                           ^
2 errors

Why?

like image 904
Dog Avatar asked May 16 '13 19:05

Dog


People also ask

How do I access static nested class?

They are accessed using the enclosing class name. For example, to create an object for the static nested class, use this syntax: OuterClass. StaticNestedClass nestedObject = new OuterClass.

Can Nested classes be static?

Terminology: Nested classes are divided into two categories: non-static and static. Non-static nested classes are called inner classes. Nested classes that are declared static are called static nested classes. A nested class is a member of its enclosing class.

Can Java inner class be static?

Inner classes are non-static member classes, local classes, or anonymous classes. In this tutorial you'll learn how to work with static member classes and the three types of inner classes in your Java code.

What is non-static nested class in Java?

A non-static nested class is a class within another class. It has access to members of the enclosing class (outer class). It is commonly known as inner class . Since the inner class exists within the outer class, you must instantiate the outer class first, in order to instantiate the inner class.


2 Answers

This won't work if A is in the default package. However, you could add a package declaration:

package mypackage;

and use

import static mypackage.A.B.*;

The static import syntax from from the JLS is given:

SingleStaticImportDeclaration: import static TypeName . Identifier ;

where TypeName is required to be full qualified.

In Using Package Members the static import syntax is given with package name included:

import static mypackage.MyConstants.*;

It is recommended to use static imports very sparingly.

like image 195
Reimeus Avatar answered Sep 30 '22 04:09

Reimeus


It should be

import <the-package-for-the-class-A>.A.B.*;

If A is in the default package, this will fail.

Last, it's not a good practice to import *. Just import only the things that you need, in this case - import static <the-package-for-the-class-A>.A.B.x; if you're gonna use only the x variable.

like image 41
Konstantin Yovkov Avatar answered Sep 30 '22 04:09

Konstantin Yovkov