1

I'm new to Java.

I was reading about Encapsulation concept in Object Oriented Programming.

While reading, I saw a line telling that :

If constructor of a class is declared as private, it will cause some problems.

But it didn't tell what kind of problems could occur.

Can anyone tell what kind of problems are there with private constructor ?

Anish B.
  • 9,111
  • 3
  • 21
  • 41
  • 1
    post the line that you saw here. – karan Sep 25 '20 at 04:29
  • 2
    Quite simple but informative on the matter: https://beginnersbook.com/2013/12/java-private-constructor-example/ and https://stackoverflow.com/questions/2816123/can-a-constructor-in-java-be-private – Wololo Sep 25 '20 at 04:32
  • This seems like the world upside down to me. It's better to learn what purpose private constructors have. Any code can cause problems, if you try to learn things from that approach you're in for a long ride. – Gimby Sep 25 '20 at 13:39

3 Answers3

1

When you declare a constructor of a class as 'private', you will not be able to create new instances "objects" of that class. This is a problem if you do want to create new instances of the class, but this implementation is useful when making a Singleton Design Pattern.

If you are interested in knowing more about design patterns, I can share some resources with you.

Here is a book by Carlos E. Otero that covers the topic of design patterns: https://books.google.com.tr/books?id=IL6FBLJn69UC&printsec=frontcover&redir_esc=y#v=onepage&q&f=false

Omar
  • 11
  • 4
0

On declaring a constructor as private you can't instantiate the class using default constructor. So, you need to create a constructor with public to access it outside.

Vishal V
  • 215
  • 1
  • 8
0

Simple words, object or instance can't be created for that class.

As soon as, you write this statement below. For example

SomeClass c = new SomeClass(); // this will give an exception.

Basically, private constructors are used for making singleton classes.

Anish B.
  • 9,111
  • 3
  • 21
  • 41