Reputation: 431
I saw someone write:
The visibility of protected members in subclasses can be modified.
Then I was confused, I know the access modifier of a method in a parent class could be modified in its implementation, see below:
class Parent {
protected void m1(){}
}
class SubClass extends Parent {
@Override
public void m1() {
super.m1();
}
}
But I don't know how to modify the protected access modifier of a member variable to public in the subclass. What is the code implementation like?
Upvotes: 1
Views: 1499
Reputation: 1051
Access Modifiers can be changed in child class but there are some certain rules which have to follow-
There are four types of access modifiers available in java:
Default – No keyword required
Private
Protected
Public
Method Overriding with Access Modifiers Their is Only one rule while doing Method overriding with Access modifiers i.e.
Rule : If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.
Access modifier restrictions in decreasing order:
private
default
protected
public
i.e. private is more restricted then default and default is more restricted than protected and so on.
We can change the access level of fields, constructors, methods in subclass by applying the access modifier on it.
Example:
class Parent {
private void m1(){}
void m2(){}
protected void m3(){}
public void m4(){}
}
class SubClass extends Parent {
/*
@Override
private void m1() { super.m1(); } // not allow any modifier shows compile time error
*/
@Override
void m2() { super.m2(); } // allow default, protected, public only
@Override
protected void m3() { super.m3(); } // allow protected, public only
@Override
public void m4() { super.m4(); } // allow public only
}
Upvotes: -2