在J2SE 5.0版本中,java語(yǔ)言引入了很多新的特性,本文將主要介紹static import。static import主要解決的問(wèn)題是方便開(kāi)發(fā)人員創(chuàng)建和使用全局的常量以及靜態(tài)的方法。要使用這一新的特性您應(yīng)該首先從java.sun.com下載最新的j2sdk 5.0。
在《effective java》中作者曾經(jīng)談到在接口中定義常量是很糟糕的一種使用方法,我們應(yīng)該始終使用接口來(lái)定義類型。但是在實(shí)際開(kāi)發(fā)工作中還是有很多人這樣使用接口,他們這樣做的原因是這樣定義常量使用起來(lái)很方便。例如如下定義方式:
public interface BadIrrationalConstants {
public static final double SQRT_TWO = 1.414;
public static final double SQRT_THREE = 1.732;
}
public interface BadTranscendentalConstants {
public static final double PI = 3.14159;
public static final double E = 2.71828;
}
假如你想在自己的類中使用這些接口中定義的常量的時(shí)候,那么你必須要實(shí)現(xiàn)這些接口。比如
public class BadUSEOfConstants implements
BadTranscendentalConstants, BadIrrationalConstants {
public static double sinPiOverFour() {
return SQRT_TWO / 2;
}
public static void main(String[] args) {
System.out. System.out.println("The sin of Pi/4 is about " +
sinPiOverFour());
}
}
這樣這些常量就變成你的類的一部分了,假如這個(gè)類不是final的話,其它的類繼續(xù)了這個(gè)類又使得它繼續(xù)了這些常量,但是這也許不是用戶需要的結(jié)果。
針對(duì)這樣的情況,我們可以這樣做,那就是在一個(gè)類中定義這些常量,使用的時(shí)候可以通過(guò)ClassName.variableName來(lái)訪問(wèn)他們。例如
package staticEx;
public class IrrationalConstants {
public static final double SQRT_TWO = 1.414;
public static final double SQRT_THREE = 1.732;
}
package staticEx;
public class TranscendentalConstants {
public static final double PI = 3.14159;
public static final double E = 2.71828;
}
現(xiàn)在J2SE 5.0提供了靜態(tài)導(dǎo)入的功能,你只需要在import要害字后面寫(xiě)一個(gè)static要害字就可以直接使用類中定義的常量了,例如
import static staticEx.IrrationalConstants.SQRT_TWO;
import static staticEx.IrrationalConstants.SQRT_THREE;
import static staticEx.TranscendentalConstants.PI;
當(dāng)然你也可以使用.*的格式,例如
import static staticEx.IrrationalConstants.*;的格式
package staticEx;
import static staticEx.IrrationalConstants.SQRT_TWO;
import static staticEx.IrrationalConstants.SQRT_THREE;
import static staticEx.TranscendentalConstants.PI;
public class ConstantsWithStaticImport {
public static double sinPiOverFour() {
return SQRT_TWO / 2;
}
public static void main(String[] args) {
System.out.println("Pi is approximately " + PI);
System.out.println("The sin of Pi/4 is about " +
sinPiOverFour());
}
}
運(yùn)行該程序會(huì)得到
Pi is approximately 3.14159
The sin of Pi/4 is about 0.707
在這里提醒大家一下,假如你過(guò)多的使用.*的樣式,那么可能會(huì)給程序的可讀性帶來(lái)負(fù)面的影響。因?yàn)槟愫茈y看出這個(gè)變量在哪里定義的。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注