简体   繁体   中英

access to local variable in inner class

package geometry;

public class Hypotenuse {
    public InnerTriangle it = new InnerTriangle();

    class InnerTriangle {  
        public int base;
        public int height;
    }
}

Which statement is true about the class of an object that can reference the variable base?

A. It can be any class.

B. No class has access to base.

C. The class must belong to the geometry package.

D. The class must be a subclass of the class Hypotenuse

This is from SCJP Dumps, Answer is "C". As my knowledge answer should be "B" because inner class has local variable called "base" and it has scope only in the inner class. Even if i want to usethis variable in "geometry" class i am not allowed to do it.

Please guide me if i am wrong?

The class InnerTriangle has a "package level" scope since you have not specified any explicit access modifier. This means members in the class as well as members in the package are allowed access to the class.

That is why "C" is the right answer.

base is a public variable and the outer class is a public class. Therefore, all classes in the scope of the inner class will have access to it. The inner class has package scope, so base 's scope is the package.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM