×

Loading...

Private constructor is useful on some occasion.

本文发表在 rolia.net 枫下论坛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
Report

Replies, comments and Discussions: