The inner class is the class defined inside a class, and the inner class can be declared as public, private, protected. If the inner class defined as private and protected, can outer class access the members of inner class? and can inner class access members of outer class?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Explanation is in context of regular inner class[Regular inner classes cannot have static members declared inside them]
You can access any field of outer class from inner class directly.
Even Outer class can access any field of Inner class but through object of inner class.
In general, you can (access private fields on inner classes and vice-versa). The following code compiles under Eclipse:
That said, you can configure your IDE/compiler to treat accesses to such fields as errors (in Eclipse this setting is called "Access to non-accessible member of an enclosing type", under Preferences -> Java -> Compiler -> Error/Warnings -> Code Style)
Yes. These qualifiers will only affect the visibility of the inner class in classes that derive from the outer class.
Yes, including the ones declared
private
, just as any instance method can.(Joshua Bloch, from the book Effective Java.)
As for your questions: it is very easy to test by yourself. But the answer is yes (even for
private
members), as long as you are not trying to access a non-static member (other than from a reference) from a static context, or trying to access a member which is in an inaccessible scope.That is, very much as one would expect =).
Yes! You can access both an inner class member from outer class, and vice-versa(irrespective of the access modifier). However, for a static nested class you cannot access its field just by the field name, and you need to access it like
though you can access the static fields of the outer class from the inner class directly by the fields names.