Private constructor is useful on some occasion.

sailor (Sailor)
本文发表在 rolia.net/zh 相约加拿大网上社区枫下论坛
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.
更多精彩文章及讨论,请光临枫下论坛. 网址: rolia.net/zh
2000-11-26 -04:00
This post has been archived. It cannot be replied.
Page address has been copied. To share, click to copy page address.
Share Online by QR Code

Back To Topic: dummy question about private constructor

Back To Forum: HOME枫下论坛枫下论坛主坛工作学习IT技术讨论