Private constructor is useful on some occasion.

sailor (Sailor)
<本文发表于: 相约加拿大:枫下论坛 >
For example, consider such a class:

public class House
private int floors ;

public House(int f) { this.floors = f; }

Here, the field "floors" means the number of floors of house. And as you see, the constructor is public.

Now consider the following situation, if someother programs create a House object in this way:

House h1 = new House(-4) ;

Obviously it's non-sense -- the number of floors cannot be negative. So, how to avoid such situation? This is why the private constuctor was introduced. Please see the following solution:

public class House
private int floors ;

private House(int f) { this.floors = f; }

static public House createInstance(int f)
{if (f < 1) return null ;
House h = new House(f) ;
return h ; }

In this case, the static public method "createInstance" does the examination and create a new object of House.

Now if the user writes codes like this:

House h1 = House.createInstance(4) ;
House h2 = House.createInstance(-4) ;

h1 will be an meaningful object and h2 is still null.

Hope my explaination is clear.
<本文发表于: 相约加拿大:枫下论坛 >

2000-11-26 -04:00

回到话题: dummy question about private constructor

回到论坛: HOME枫下论坛枫下论坛主坛工作学习IT技术讨论