public class Test{
private static String ss1 = ident("aaaaa");
private static String ss2 = ident("bbbbb");
public static String ident(String s){
return s;
}
}
哪位大哥讲一下这样写的好处是什么? 谢谢!
就我看到lz你贴出的代码而言
没有什么必要
ident这个静态方法执行的唯一的意义就是
“静态方法执行之前 所有的静态域必须初始化完毕”
谈不上好处
如果方法没有static修饰符
那必须使用类的实例来调用如
Test test = new Test();
test.ident("");
而有了static修饰符,这个方法就是类的方法了
直接使用Test.ident("")来调用即可
单例模式也是通过static来实现的
[code="java"]
public class SingleTon
{
private static SingleTon instance = new SingleTon();
private SingleTon() {}
public static SingleTon getInstance()
{
return instance;
}
}
[/code]
这种大写方式的域 只是为了内部使用
比如判断某个字符串的内容等于aaaa 而这个判断出现了多次
不必再处处使用"aaaa".equals(str)
而只需要S_TEST.equals(str)就行了
其实更多的情况下 是使用public来修饰的
这样再其他类中也能够应用到这个常量了