[英]JAVA, Should I use “import”?
public class launcher{
public static void main(String[] args){
javax.swing.JOptionPane.showMessageDialog(null,"HelloWorld");
}
}
public class launcher{
public static void main(String[] args){
System.out.println("HelloWorld");
}
}
public class launcher{
public static void main(String[] args){
int a = java.util.Random.nextInt(10);
}
}
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" Code1和Code2在没有“ import java.swing.JOptionPane”或“ import System.out.println”的情况下可以很好地工作
But, Code3 doesn't work well. 但是,Code3不能很好地工作。
Should I use like Code4? 我应该像Code4一样使用吗?
Your problem in "Code3" doesn't have anything to do with importing Random
or using its fully qualified name. 您在“ Code3”中的问题与导入
Random
或使用其完全限定名称无关。
Your problem is that nextInt()
is not a static method. 您的问题是
nextInt()
不是静态方法。 "Code4" works because you create an instance of Random
and run the nextInt()
method on it, not because you've imported the class. “ Code4”之所以起作用,是因为您创建
Random
的实例并在其上运行nextInt()
方法,而不是因为已导入了该类。
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: 如果像这样重新编写,则“ Code3”将起作用:
public class launcher{
public static void main(String[] args){
java.util.Random rr = new java.util.Random();
int a = rr.nextInt(10);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.