my dog learned polymorphism
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes ///private constructor/// Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "///private constructor///" Watch "///private constructor///" New topic

///private constructor///

chao-long liao
Ranch Hand

Joined: Jul 29, 2001
Posts: 78
Constructor can be private,but why??how to use private constructor??

public class Fred {
int x;
private Fred (int xval) {
x = xval;

public class F extends Fred{
Fred a= new Fred(2);
} No constructor matching Fred() found in class Fred.
public class F extends Fred{
^ No constructor matching Fred(int) found in class Fred.
Fred a= new Fred(2);
2 errors

How to use the private constructor to creat a new object?
Amir Ghahraei

Joined: Jun 20, 2002
Posts: 5
By specifying a constructor as private, it means that you cannot create object of that class.
in other words it cannot be instantiated.
the reason you may want to do this is for example if you have a private default constructor (which does some arbitrary work for the class) and a public non-default constructor. clients can then only call the non-default constructor to create objects of that class.
Manish Hatwalne
Ranch Hand

Joined: Sep 22, 2001
Posts: 2591

private/protected constructors are used so that you have more control over how the instances of class are created, typically by using factory methods.
Math is a final class (so can not be extended), which has such a constructor, so you can use its static methods but can not instantiate it.
Abstract class would ensure that the class can not be instantiated, but the u won't be able to make it final.
- Manish
Alan Chong
Ranch Hand

Joined: Jun 05, 2002
Posts: 106
At least in the other constructors the private
constructors can be called like :
this.(Whatever w);
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Originally posted by chao-long liao:
Constructor can be private,but why??how to use private constructor??

A private member can't be invoked outside of the implementing class. The same holds true for a private constructor. By making a constructor private, that constructor can only be used by the class, itself. This is used in the context of a singleton pattern. This can be used to gain control over how and when an instance of the class is created.

SCJP Tipline, etc.
chao-long liao
Ranch Hand

Joined: Jul 29, 2001
Posts: 78
Thanks you all.
I agree. Here's the link:
subject: ///private constructor///
It's not a secret anymore!