In Java- “Static Members of the default package cannot be imported”- Can some one explain this statement?

后端 未结 2 436
臣服心动
臣服心动 2020-12-15 23:06

In Java- \"Static Members of the default package cannot be imported\"- Can some one explain this statement? It would be better if its with an example. I am not sure if it ha

2条回答
  •  天涯浪人
    2020-12-15 23:43

    as @kageb Brasee mentions : It is true that you cannot do the static import or non-static import of the class which is in a default package.

    but there is a case where you can use the class (of default package) in another class: -> And this can only be done if and only if the class (in which you want to use the class of default package) is also present in a default package

    if both the classes are in default packages (no matter at what location they are present) then you can use them (note : we are not import them just using them)

    eg. if i want to import a class temp.class (which is in a default package) located at Home/files/temp.class into my program use.java

    then just set the CLASSPATH while compiling it you can do that in two ways : permanent set OR temporary set (Not using technical terms )

    permanent set : by setting the CLASSPATH (which is an environment variable) variable (different methods to do that for different OS's) -> for mac - - > export CLASSPATH=Home/files/ in this method the CLASSPATH environment variable is set till your terminal is open

    so in this case :

     export CLASSPATH=Home/files/
     javac use.java
     java use
    

    temporary set : in this method we use either of two option provided for both java and javac (java compiler) tool and they are -classpath and -cp (both these do the same job, its just -cp is short for the -classpath), in this method of setting classpath for the other files the main difference is that in this type the address(path) of the file is set only for the time period while that command (operation) is executing as soon as the statement execution complete the value of CLASSPATH(the environment) -> again reaches to the same path as it was earlier,

    Note: by default the CLASSPATH is . (i.e. representing the same directory)

    And in this case :

     java -cp .:Home/files use.java    // Note: don't forget . and : is for separating the different paths
     java use
    

    Hope it helped :)

提交回复
热议问题