Home >Java >javaTutorial >The impact of Java function access modifiers and method overriding
The access permission modifiers of overridden methods in subclasses must be the same or broader: the access permissions of subclass methods can be broader than those of parent class methods (for example, from protected to public). Subclass methods cannot have more restricted access than superclass methods (for example, from public to protected).
The impact of Java function access modifiers and method overriding
Access modifiers control the access of Java methods Accessibility. They are of four types:
When overriding a method in the parent class, overriding in the child class Methods must have the same or wider access modifier. This is because the overridden method is based on the parent class method, so it cannot be more restricted than the parent class method.
Practical case
The following is a parent class:
public class Parent { protected void show() { System.out.println("Parent class show()"); } }
Now, consider the following subclass, which overrides the # in the parent class ##show() method. Note that the access modifier of the
show() method is changed from
protected to
public:
public class Child extends Parent { @Override public void show() { System.out.println("Child class show()"); } }Due to the
show of the parent class The () method is
protected, and the
show() method of the subclass must also be
protected or
public. Setting it to
public qualifies as a method override because it has wider access than the parent class method.
Child class show()This is because the overridden method in the
Child class is called because it has wider access (
public).
The above is the detailed content of The impact of Java function access modifiers and method overriding. For more information, please follow other related articles on the PHP Chinese website!