Reputation: 145
Here are two statements I found concerning inner classes
JavaDocs:
As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.
On another site I found this:
A nested class, for the most part, is just that—a class declared in the definition of an enclosing class. It does not inherit anything from the enclosing class, and an instance of the nested class cannot be assigned to a variable reference to the enclosing class.
Aren't the bold marked lines contradicting? How can you not inherit a surrounding objects fields and methods and at the same time have access to its fields and methods?
Upvotes: 2
Views: 820
Reputation: 20618
Please do not see the terms nested class and inner class as an opposite or something similar. In fact, a nested class simply describes all sorts of classes that are declared inside another class:
Non-static nested classes are called inner classes. There are three types of them (see JLS §8.1.3 for more info):
The first paragraph you quoted explains that an inner class has access (read: access, not inherit) to the methods and fields of the enclosing instance. Note, it is about an instance, not the class.
The second paragraph tries to explain that there is no relationship between a class and a nested class inside it, except for their locations.
Upvotes: 2
Reputation: 3688
No, they do not conflict. Look at the following example:
public class A {
public void foo() {
//some code
}
public class B {
public void bar() {
foo();
}
}
}
In this example, the innerclass B
can access the method of A
(or any of its' fields, actually), but in no way does inheritance takes place.
For instance, the following change to B
would result in a compilation error:
public class B {
public void bar() {
super.foo();
}
}
Because B
does not inherit from A
. It can access its' instance members, but it does not extend (inherit) from it.
Upvotes: 4