欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Java之静态导包,java静态导

来源: javaer 分享于  点击 38077 次 点评:170

Java之静态导包,java静态导


Java Static Import

First lets understand what does “java import” does to your java program!Conseder the java import statements:

Java statement(1) gives you a license to use Classa inside the whole program without the package reference. That is you can use like ClassA obj = new ClassA(); or ClassA.getStatic(); Java statement (2) allows you to use all the classes that belong the imported package in the above manner. That is without the package reference.

If you don’t use import statement,you can still use the classes of that package. But you should invoke it with package reference wherever you use.

That is like, package.ClassA obj = new package.ClassA(); - looks very ugly isn’t it?

Now coming to the static import part. Like the above ugly line we have been unknowingly using (abusing) the java static feature.

Consider the java example:double r = Math.cos(Math.PItheta);
How about writing the same java code likeL double r = cos(PI
theta); - looks more readable right?

This is where static import in java comes to help you.

Import static java.lang.Math.PI;
Import static java.lang.Math.cos;
Do the above static imports and then you can write it in the more readable way!

Java Static import

The normal import declaration imports classes form packages, so that they can be used without package reference. Similarly the static import declaration imports static imports static members from classes and allowing them to be used without class reference.

Now, we hava got an excellent java feature from java 1.5. Ok now we shall see how we can abuse this!

Can I static import everything?

Like,import static java.lang.Math.*;- yes it is allowed! Similarly you do for class import.

Please don’t use this feature, because over a period you may not understand which static method or static inside the java program. The program may become unreadable.
General guiderlines to use static java import:

相关文章

    暂无相关文章
相关栏目:

用户点评