2

As in C++ protected members were becoming private in private inheritance . so I am very confused what happens in Java . do here access specifiers remain same or what? like

if suppose below code exists then now shiva will still remain protected inside classB ? can we again use it in classC ?

Any help will be appreciated.

package package1
class classA
{
protected shiva;
}

////////////////////////
import package1
package package2
class classB extends classA
{}

//////////////////////
import package2
class classC extends classB
{}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Shivangi
  • 43
  • 3
  • In java, the inheritance is similar to the C++ public virtual inheritance. So, all access modifiers will remain the same – Sohaib Jundi Jul 19 '19 at 06:02

3 Answers3

5

Yes, You can use it.

            │ Class │ Package │ Subclass │ Subclass │ World
            │       │         │(same pkg)│(diff pkg)│ 
────────────┼───────┼─────────┼──────────┼──────────┼────────
public      │   +   │    +    │    +     │     +    │   +     
────────────┼───────┼─────────┼──────────┼──────────┼────────
protected   │   +   │    +    │    +     │     +    │         
────────────┼───────┼─────────┼──────────┼──────────┼────────
no modifier │   +   │    +    │    +     │          │    
────────────┼───────┼─────────┼──────────┼──────────┼────────
private     │   +   │         │          │          │    

 + : accessible         blank : not accessible

For more reference, please find the answers to this question here. It seems to me similar.

g3ntl3m3n
  • 73
  • 9
1

Yes, you can use the protected field in the subclass.

1

Protected access modifier lies between the public and default access modifier. It can be accessed outside the package but only through subclasses.

Refer this link for more clarity.

https://www.tutorialride.com/core-java/inheritance-access-modifiers-in-java.htm

So yes you can use it in the subclasses.