0

Can i access all the members(both static and instance) in a class using like this

import java.lang.System.*;

If i want to import a class then syntax should be import java.io.PrintSteam Then we can access printstream and for accessing static members import static should be used

import java.lang.System.* is compiled successfully but not able to access any methods,instance variables,static variables from the class,then what is imported using above line.

Shashaank V V
  • 720
  • 1
  • 7
  • 19
  • @ernest_k,Thank you,yes,static is for importing static members,how to import instance members into other class. import java.lang.System.*; is compiled,what is imported if not instance members – Shashaank V V Jul 15 '18 at 18:32
  • 1
    You can't import instance members like that, simply because the instance on which to call/read them is unknown. – ernest_k Jul 15 '18 at 18:34
  • 1
    @GhostCat,Question is different,Please explain what is imported using import java.lang.System.*; – Shashaank V V Jul 15 '18 at 18:34
  • @ernest_k,ok but why import java.lang.System.* is compiled and what is imported ? – Shashaank V V Jul 15 '18 at 18:36
  • Yes,import would not fail ,but why the compiler successfully compiles import java.lang.System.*; and what is imported? – Shashaank V V Jul 15 '18 at 18:40
  • I think I understand your 'why' question better. Compilation doesn't fail because the wildcard doesn't match anything. But it would be valid because `System` could have nested types (which could be possibly targeted by the `System.*` import). – ernest_k Jul 15 '18 at 18:45
  • @ernest_k,Thank you – Shashaank V V Jul 15 '18 at 18:48

2 Answers2

2

Lets start with why it is valid.

Quoting the JLS:

TypeImportOnDemandDeclaration:

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.

The JLS says it valid to "import on demand" (wildcard import) a type, (such as java.lang.System).

Why does that make sense? Because a class (type) can have inner classes.

So when you have

public class A {
  public static class InnerB

the import A.* will make that InnerB available. See here for more thoughts on this.

Community
  • 1
  • 1
GhostCat
  • 137,827
  • 25
  • 176
  • 248
1

You can use static import like below.

import static java.lang.System.*;
Alien
  • 15,141
  • 6
  • 37
  • 57