“静态”是什么? “导入”之后的修饰符意思? [英] What does the "static" modifier after "import" mean?

查看:161
本文介绍了“静态”是什么? “导入”之后的修饰符意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当像这样使用时:

import static com.showboy.Myclass;

public class Anotherclass{}

<$ c $之间有什么区别? c> import static com.showboy.Myclass 和 import com.showboy.Myclass

推荐答案

参见文档


静态导入声明是
类似于普通导入
声明。如果正常导入
声明从
包中导入类,允许它们在没有包资格的情况下使用
,则
静态导入声明从类中导入
静态成员,允许
它们在没有
资格的情况下使用。

The static import declaration is analogous to the normal import declaration. Where the normal import declaration imports classes from packages, allowing them to be used without package qualification, the static import declaration imports static members from classes, allowing them to be used without class qualification.

那么什么时候应该使用静态导入?
非常谨慎!只有当你用
时才使用它,否则很想宣告本地
的常量副本,或滥用
继承(Constant Interface
Antipattern)。换句话说,如果您需要从一个或两个
类中频繁访问
静态成员,请使用
。如果你过度使用静态
导入功能,它可能使你的
程序不可读且不可维护,
使用你导入的所有
静态成员来污染它的命名空间。
你的代码的读者(包括你,你写完几个月后的
)将不知道
哪个类静态成员来自
。从类中导入所有静态
成员可能是
,对可读性特别有害;
如果您只需要一个或两个成员,
单独导入它们。适当地使用
,静态导入可以使
你的程序更具可读性,通过
删除重复
类名的样板。

So when should you use static import? Very sparingly! Only use it when you'd otherwise be tempted to declare local copies of constants, or to abuse inheritance (the Constant Interface Antipattern). In other words, use it when you require frequent access to static members from one or two classes. If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from. Importing all of the static members from a class can be particularly harmful to readability; if you need only one or two members, import them individually. Used appropriately, static import can make your program more readable, by removing the boilerplate of repetition of class names.

这篇关于“静态”是什么? “导入”之后的修饰符意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆