Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"The constructor is not visible" error

I have two classes :

First, with one constructor :

public class First {

    First (ObjectA myObjectA) {
        //do stuff
    }
}

And Second, with two constructors :

public class Second {

    Second (ObjectB myObjectB) {
        //do something...
    }

    Second (ObjectC myObjectC) {
        //do something else...
    }
}

When I want to instantiate my First class, Eclipse generates me an error ("The constructor is not visible"), I have to add public to the constructor of First :

First first = new First(myObject); //Error : "The constructor is not visble"

But when I instantiate my Second class, I have no error :

Second second = new Second(myObjectC); //No error...

Notes: I instantiate First in an other class, but I instantiate Second in First. First and Second are in the same package.

Can you explain me why ?

like image 451
BnJ Avatar asked Aug 27 '14 14:08

BnJ


People also ask

What if constructor is not public?

A private constructor in Java is used in restricting object creation. It is a special instance constructor used in static member-only classes. If a constructor is declared as private, then its objects are only accessible from within the declared class. You cannot access its objects from outside the constructor class.

What happens when constructor is not defined?

However, it's important to know what happens under the hood when no constructors are explicitly defined. The compiler automatically provides a public no-argument constructor for any class without constructors. This is called the default constructor.

What happens if a constructor is declared private?

If we declare a constructor as private we are not able to create an object of a class. We can use this private constructor in the Singleton Design Pattern.


2 Answers

No access modifier for your constructor makes it package private. Assuming that First and Second are in the same package, you can call Second's constructors from first. Another class from another package, however, cannot access any of the constructors.

like image 184
J4v4 Avatar answered Sep 28 '22 06:09

J4v4


Your class must be in 2 packages. If you don't mention any explicit access modifier Java will consider them as default access modifier. Then you can only access them through the same package only.

Access Modifiers (From least access to highest access)

  1. private - Only within same class
  2. default - Only within same package
  3. protected - same package + children classes in other packages
  4. public - From anywhere
like image 34
Thusitha Thilina Dayaratne Avatar answered Sep 28 '22 07:09

Thusitha Thilina Dayaratne