Get your CodeRanch badge!*
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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "///private constructor///" Watch "///private constructor///" New topic
Author

///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);
}

F.java:1: No constructor matching Fred() found in class Fred.
public class F extends Fred{
^
F.java:2: 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
Greenhorn

Joined: Jun 20, 2002
Posts: 5
Ok,
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: 2578

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.
HTH,
- 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.
Corey


SCJP Tipline, etc.
chao-long liao
Ranch Hand

Joined: Jul 29, 2001
Posts: 78
Thanks you all.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: ///private constructor///
 
Similar Threads
why cannot use protected in this class definition?
Access Modifiers
inner class
why cannot use protected in this class definition?
Sample Questions from Sun