欲编写一个"总统"类,其构造器中可以包含一系列的创建"总统"的步骤: class President { public President(){ //... } } 这样做的一个问题是"总统"只能有一个,但其他程序使用这个类时却可以用new President()创建多个不同的"总统"。为了防止多个“总统”被创建出来,可以将President的构造器由public类型改为private类型,根据前面的访问控制规则,这样该构造器就只能在类President内部使用,而在类之外就不可使用了。 class President { private President(){ //... } } 这样,在其他类中就无法用President创建对象了,但为了仍能使用President对象,可以在类President中通过显示初始化创建好,如下 class President{ String name; static President x=new President(); private President(){ name="xxx"; } class Test{ public static void main (String args[ ]){ //President x= new President(); President p=President.x; System.out.println(p.name); } } 在President中定义了变量x,其显示初始化中创建了President对象,由于在类Test中无法创建President对象,因而President中的x定义为static类型,以便通过类名直接访问。这样,类President保证了使用时只能通过President.x来获取对象,该对象在整个程序中只有一个。程序中任何地方都不可以创建对象,但可通过President.x来执行“总统”对象的方法、访问其成员变量。 这样使用还有一些不足,如果在程序中某一块不小心写了President.x=null,且没有其他变量指向该“总统”对象,则“总统”对象会丢失而无法再访问。因而可进一步将变量x也封装起来,只允许通过方法来访问。如下。 class President{ String name; private static President x=new President(); private President(){ name="xxx"; } static President getPresident() { return(x); } } class Test{ public static void main (String args[ ]){ President p=President.getPresident(); System.out.println(p.name); } }

评论