简体   繁体   中英

JAVA, Should I use “import”?

Code1

public class launcher{
    public static void main(String[] args){
        javax.swing.JOptionPane.showMessageDialog(null,"HelloWorld");
    }
}

Code2

public class launcher{
    public static void main(String[] args){
        System.out.println("HelloWorld");
    }
}

Code3

public class launcher{
    public static void main(String[] args){
        int a = java.util.Random.nextInt(10);
    }
}

Code4

import java.util.Random;
public class launcher{
    public static void main(String[] args){
        Random rr = new Random();
        int num = rr.nextInt(10);
    }
}

Code1 and Code2 work well without "import java.swing.JOptionPane" or "import System.out.println"

But, Code3 doesn't work well.
Should I use like Code4?

Your problem in "Code3" doesn't have anything to do with importing Random or using its fully qualified name.

Your problem is that nextInt() is not a static method. "Code4" works because you create an instance of Random and run the nextInt() method on it, not because you've imported the class.

All that importing a class really does is save you from having to write out the package every time you want to use it. It doesn't change the way you can invoke methods on that class.

"Code3" would work if you re-wrote it like this:

public class launcher{
    public static void main(String[] args){
        java.util.Random rr = new java.util.Random();
        int a = rr.nextInt(10);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM