[Basic Java] What happens if you don't use public when declaring the creator?

Asked 2 years ago, Updated 2 years ago, 84 views

I'm a student of Java.

I learned that you use public to declare a constructor.

However, when coding alone, there is no error even if the public is omitted (without typing), and the corresponding constructor can be used in other classes in the same package, so I asked because I was curious about the case.

I tried googling about this, but I'm confused whether what I understood is right or not.

First of all, I think it's one of the two cases.

(I would appreciate it if you could explain which of the two cases is correct, or which is which if not both.)

1. If Java recognizes that it used public on its own even if public is omitted,

2. If you omit public and declare a constructor, the constructor is declared as default, not public, and for this reason, if the constructor is available in the same package

Thank you for your answer.

For reference, the meaning of omitting public when declaring a creator is

If you used public when declaring a constructor

public car(String name) {

}

Public omitted when declaring constructor

car(String name) {

}

It literally means declaring a constructor without writing public.

java constructor

2022-09-22 13:27

1 Answers

2 default If the access controller is not set separately, variables and methods without the access controller become the default access controller and can be accessed only within the package.

Access Modifier https://wikidocs.net/232


2022-09-22 13:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.