gpt4 book ai didi

java - static 关键字在导入 java.lang.System 类中的作用是什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:46:04 25 4
gpt4 key购买 nike

导入System类时不明白关键字static的含义:

import static java.lang.System.*

我正在阅读有关 Java 的书,里面写着:

Any import declaration that doesn't use the word static must start with the name of a package and must end with either of the following:

  • The name of a class within that package
  • An asterisk (indicating all classes within that package)

For example, the declaration import java.util.Scanner; is valid because java.util is the name of a package in the Java API, and Scanner is the name of a class in the java.util package.

Here’s another example. The declaration import javax.swing.*; is valid because javax.swing is the name of a package in the Java API, and the asterisk refers to all classes in the javax.swing package.

我有以下代码:

public class Addition {

public static void main(String[] args) {
double num;
num = 100.53;

num = num + 1000;

// So when I want to import the whole package java.lang as written in the book, it doesn't work:
// import java.lang.*;
// or like this:
// import static java.lang.*;
// NetBeans in both cases doesn't see these abbreviated names `out` and throws errors. Why?
out.print("The result is ");
out.print(num);
out.println(" .");
}
}

当我以这种方式导入时它起作用了:

import static java.lang.System.out;
import static java.lang.System.*

但是当我尝试这样做时不起作用:

import java.lang.System.out;
import java.lang.System.*

在这种特殊情况下,static 关键字的含义是什么?

为什么 import java.lang.*; 没有导入包含 System 类的整个包?

最佳答案

static 导入允许您这样写:

out.print("The result is ");

而不是这个:

System.out.print("The result is ");

参见例如http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html .

关于java - static 关键字在导入 java.lang.System 类中的作用是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10756657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com