Home  >  Article  >  Java  >  The impact of Java function access modifiers and method overriding

The impact of Java function access modifiers and method overriding

王林
王林Original
2024-04-26 09:27:01886browse

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).

Java 函数的访问权限修饰符之与方法重写的影响

The impact of Java function access modifiers and method overriding

Access modifiers control the access of Java methods Accessibility. They are of four types:

  • public: accessible everywhere
  • protected: accessible within the same package and subclasses
  • default (not explicit modifier): accessible in the same package
  • private: only accessible inside the class

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.

Running both classes will print the following output:

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn