Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

///private constructor///

 
chao-long liao
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2591
Android Firefox Browser Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
At least in the other constructors the private
constructors can be called like :
this.(Whatever w);
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
chao-long liao
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks you all.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic