D
D
Dmitry2022-03-07 10:41:06
Java
Dmitry, 2022-03-07 10:41:06

Why does protected in Java work the way it does?

I must say right away that my main language is C #, so I think in its paradigm.
There, access modifiers work similarly to Java, with the exception of protected. In C#, it means "available only in the class and its descendants", and the namespace (some analog of a package in Java) does not play a role. Those. it turns out a sort of "private for me and my descendants."

Those. scenarios are as follows:
1. You need access from anywhere - write public.
2. You need access only inside the class - write private.
3. You need access only inside the class and descendants - write protected.
4. You need access from anywhere, but only within the namespace ("package") - write internal.

In Java, protected is access to everyone in the same package, and in other packages, only to descendants.
I can't figure out what's the point of giving full access to everyone in the same package? It turns out that we have scenario 3.

For example, I want to create an Employee class (with potential subclasses OutsourceEmployee, OwnEmployee), it has the First Name, Last Name fields. I want them to be inherited, so I must declare them as protected. But then they will become visible from outside the classes themselves, and the conditional class X, having received a reference to the employee, will be able to change the First Name or Last Name field directly, bypassing the setter methods.

In general, now for me such protected looks absurd. Explain what is the matter, why is it like this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Roo, 2022-03-07
@xez

But then they will become visible from outside the classes themselves and the conditional class X...

This "conditional class X" is, after all, not some random class, but a class from the same package.

A
Anton Shamanov, 2022-03-07
@SilenceOfWinter

well, your employee class and its heirs may not be public, incl. will only be available inside the package and descendants.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question