public class Pvf { static boolean Paddy; public static void main(String[] args) { System.out.println(Paddy); } } |
false
分析:变量被赋予了默认值false。
4、static方法调用非static变量
public class Sytch { int x = 20; public static void main(String[] args) { System.out.println(x); } } |
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Cannot make a static reference to the non-static field xat test02.Sytch.main(Sytch.java:6)
5、
public class Sundys { private int court; public static void main(String[] args) { Sundys s = new Sundys(99); System.out.println(s.court); } Sundys(int ballcount) { court = ballcount; } } |
99
分析:私有化变量仍可以被构造方法初始化。
6、私有化的一个应用是单例设计模式
class Singleton{ private static Singleton instance = new Singleton(); private Singleton(){ } public static Singleton getInstance(){ return instance; } public void print(){ System.out.println("hello"); } } public class SingleDemo05 { public static void main(String[] args) { Singleton s1 = Singleton.getInstance(); Singleton s2 = Singleton.getInstance(); Singleton s3 = Singleton.getInstance(); s1.print(); s2.print(); s3.print(); } } |
hello
hello
hello
分析:虽然声明了3个Singleton对象,但实际上所有的对象都只使用instance引用,也就是说,不管外面如何,最终结果也只有一个实例化对象存在。此即为单例设计模式。
由此可知,只要将构造方法私有化,就可以控制实例化对象的产生。