3

I have 2 classes: class A and class B, both classes are packageless (in default package). I want to import and use A's static variable into B. How do I do that so that it compiles?

The following is not compiling:

A.java

public class A {
    public static int x = 10;
}

B.java

import static A.x;

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

Compiler output: B.java:1: error: static import only from classes and interfaces

elyor
  • 998
  • 9
  • 20
  • 3
    *How do I do that so that it compiles?* You remove the import and write `A.x`, **or** you start using packages. **Why** aren't you putting your code into packages? – Elliott Frisch Apr 24 '17 at 21:05
  • You can't, which is one of reasons why we shouldn't place classes in default package. – Pshemo Apr 24 '17 at 21:06

1 Answers1

4

This is impossible with java, you have to package them in a unique or different package.

Or you can use :

System.out.println(A.x);

You can read more in java doc about Import Declarations

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140