Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java import class System

Tags:

java

import

class

I have a question on class imports, It seems you can call a method with a reduced line if you have imported the class. I don't understand what is the name of this operation, and how is it possible...

For instance :

Why this code

public class test 
{
        public static void main  (String args[])
        {
                System.out.print("Test");
        }
}

Can be replaced by

import static java.lang.System.out;

public class test 
{
        public static void main  (String args[])
        {
                out.print("Test");
        }
}

What happens if you have also an object named "out" ?

Thanks in advance

like image 546
MisterDoy Avatar asked Jul 08 '11 13:07

MisterDoy


2 Answers

What happens is that out from external class must be referenced by full name:

String out = "Hello World";
java.lang.System.out.println(out);
like image 126
Victor Sorokin Avatar answered Oct 15 '22 17:10

Victor Sorokin


The variable out will shadow the static import and you will have to use the full name in order to use the function print.

import static java.lang.System.out;
public class Tester5 {
  public static void main (String args[]) {
    int out=0;
    out.print("Test");
  }
}

yields "cannot invoked print(String) on primitive type int. The same error is shown if out is an object.

like image 22
VirtualTroll Avatar answered Oct 15 '22 18:10

VirtualTroll