Problems with Java access rights

Source: Internet
Author: User
Tags modifier

Java access right modifier background:

About four kinds of access modifiers in Java, public, default, protected, private the scope of the work is very familiar, but encountered a piece of code:

 PackagePAC1; Public  class Parent {protected intIprotected  class Inner {           }} PackagePAC2;ImportPac1. Parent; Public  class  child extends Parent {Public   static void main(String args[]) {NewChild (). i=0; Inner i =NewParent (). New Inner (); }}
Problem

The code means that the parent class and the subclass are not in a package, the parent class has an inner class of protected, and now you want to generate the inner class object in the parent class in the child class. But found that the error was reported:

Error:(828) java: Inner()可以在pac1.Parent.Inner中访问protected
Thinking

Protected access is said, under the same package can be freely accessible, under the other package can only be accessed. It is true that Inner i = new Parent().new Inner(); there is no problem on the left, but the right side is the inner class generation method, why not visit it?
Originally I was here only to consider the parent and child package location and inheritance relationship, without regard to the inner class and child is also different packages, and inner's constructor access permissions are not public, so in different packages and no secondary relationship of child is not generated inner.

Solve
    1. In fact, the error of the report said the cause of the problem, Inner () where the package is PAC1. Parent.inner, the modifier is protected, so say Inner () can be in Pac1. Access to protected, which is the same package, is accessed in Parent.inner. It is also important to explain the mistakes of the multi-thinking newspaper.

    2. Knowing the reason, you just need to change the inner constructor to Publi.

Problems with Java access rights

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.