Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private constructor and public parameter constructor

I heard that a private constructor prevents object creation from the outside world.

When I have a code

public class Product
{
   public string Name { get;set;}
   public double Price {get;set;}
   Product()
   {
   }

   public Product(string _name,double _price)
   {
   }
}

Here I still can declare a public constructor (parameter), won't it spoil the purpose of the private constructor? When do we need both private and public constructor (parameter) in code?

I need a detailed explanation please.

like image 339
Amutha Avatar asked Apr 14 '10 18:04

Amutha


People also ask

What is the difference between private and public constructor?

Private constructors are still instance constructors - they are not static. They're no different from public constructors, except they define who can call them, just like the difference between a public and private regular method.

Can we have parameters in private constructor?

Can a Private Constructor have Parameters ? Yes. You might do that if you had some reason to have a level of indirection where there were Private variables (or whatever) in the Class that you never wanted set directly from outside an instance of the Class.

What is difference between private and public constructor in Java?

public means you can access it anywhere while private means you can only access it inside its own class. Just to note all private, protected, or public modifiers are not applicable to local variables in Java. a local variable can only be final in java.

What is the difference between private constructor and static constructor?

1. Static constructor is called before the first instance of class is created, wheras private constructor is called after the first instance of class is created. 2. Static constructor will be executed only once, whereas private constructor is executed everytime, whenever it is called.


1 Answers

The reason you would use the pattern you're describing is when you want to control how the object is instantiated.

In your example, for instance, you're saying the only way to create a Product is by specifying its name and price. This is with respect to the outside world, of course. You could also do something similar using other access modifiers, and it would have different implications, but it all boils down to controlling how you want the objects instantiated with respect to who will be doing it.

If you wanted to prevent object creation altogether you would have to make all your constructors private (or protected). That would force the object to be created from within itself (or an inherited class).

Also, as Matti pointed out in the comment below, when you define a constructor that is parameterized you don't need to specify a private default constructor. At that point it is implied.

like image 64
Joseph Avatar answered Nov 16 '22 02:11

Joseph