Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java constructor having broader access level than its class

Java specification allows a class with default access to have its constructor public access, what is the purpose of it, since it cannot be referenced outside its package?

like image 375
Dilini Rajapaksha Avatar asked May 03 '26 09:05

Dilini Rajapaksha


2 Answers

I wanted to make this a comment, but since no code tags are allowed in comments....

In regards to your comment on CristopheDs answer:

package bob;

class MySuperHiddenClass {

  public MySuperHiddenClass() {
        System.out.println("bob");
  }
}

And

package bob;
public class MyPublicClass extends MySuperHiddenClass {

}

No constructor was declared in MyPublicClass, but you can still call new MyPublicClass from any package.

like image 121
user439407 Avatar answered May 04 '26 23:05

user439407


If you are asking for why you can have public constructors: it's because you can for example call them explicitely (or implicitely) when you extend a base class.

like image 40
ChristopheD Avatar answered May 04 '26 22:05

ChristopheD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!