Shivangi
Shivangi

Reputation: 43

what happens to protected members after inheritance in java?

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
{}

Upvotes: 2

Views: 154

Answers (3)

g3ntl3m3n
g3ntl3m3n

Reputation: 73

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.

Upvotes: 5

Mohamed Yilmaz
Mohamed Yilmaz

Reputation: 66

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.

Upvotes: 1

Praveen Hassan
Praveen Hassan

Reputation: 96

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

Upvotes: 1

Related Questions