Java Static Import

Java Static Import

First lets understand what does “java import” does to your java program!
Consider the java import statements:
1) import package.ClassA;
2) import package.*;

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 java 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 whereever 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.PI * theta);

How about writing the same java code like: 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 from packages, so that they can be used without package reference. Similarly the static import declaration imports static members from classes and allowing them to be used without class reference.

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值