| Author |
Something weird about static imports
|
Sankaranarayanan Viswanathan
Greenhorn
Joined: Sep 27, 2011
Posts: 5
|
|
I have two java source files as below:
Test2.java
Test.java
My problem is I don't understand why Line 1 does not compile, but Line 2 compiles okay. The static import in Test.java does not import the class Test2 itself, but only the static members of Test2. If that is true, why does Line 2 work - Doesn't the java compiler need Test2 to be visible before it could access its instance member data? If you comment out Line 1, you will see that Test.java compiles and executes.
|
 |
Stephan van Hulst
Bartender
Joined: Sep 20, 2010
Posts: 3047
|
|
You don't need import statements unless you're actually using the name of whatever it is you're using. You're not using the name Test2 in line 2, so you don't need to import it.
Think about it. Import statements are used to tell the compiler where to find the things you're referring to.
|
 |
Sankaranarayanan Viswanathan
Greenhorn
Joined: Sep 27, 2011
Posts: 5
|
|
But, then this example below causes a compile error. I am not referring to the 'Inner' class explicitly, but yet I receive a compile error:
But, look at this one below which actually compiles and produces an output of "Inner: 10":
Why does this work?
|
 |
Stephan van Hulst
Bartender
Joined: Sep 20, 2010
Posts: 3047
|
|
|
The first fails because you're trying to access a field of a private class. Inner is private, so Test knows nothing about it. This has nothing to do with import statements.
|
 |
maganti suryanarayana
Ranch Hand
Joined: Mar 30, 2010
Posts: 53
|
|
|
What is there in line 2 just a blank place.
|
surya
|
 |
Stephan van Hulst
Bartender
Joined: Sep 20, 2010
Posts: 3047
|
|
|
Look at the comments in lines 7 and 8 of Test.
|
 |
 |
|
|
subject: Something weird about static imports
|
|
|