Home > Java > javaTutorial > body text

The impact of Java function access modifiers and method overriding

王林
Release: 2024-04-26 09:27:01
Original
831 people have browsed it

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()");
    }
}
Copy after login

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()");
    }
}
Copy after login

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()
Copy after login
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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!