2016-03-17 78 views
2

这里有两种说法,我发现有关内部类内部类继承和访问封闭类的方法/字段

的JavaDoc:

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.

在另外一个网站,我发现这一点:

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.

大胆的标志线不矛盾吗? 如何不能继承周围的对象字段和方法,并同时访问其字段和方法?

+1

继承和访问是两个不同的事情。 – SomeJavaGuy

回答

2

请不要看到嵌套类内部类作为一个相反或类似的东西。事实上,nested class只是简单地描述了各种被另一个类中声明的类:被声明为static

  1. 嵌套类被简单地称为静态嵌套类
  2. 非静态嵌套类被称为内部类。有三种类型(请参阅JLS §8.1.3获取更多信息):

    1. 非静态成员类。
    2. 本地班级。
    3. 一个匿名类。

你报的第一段解释说,一个内部类可以访问(读:访问,不能继承),以封闭实例的方法和字段。请注意,它是关于一个实例,而不是类。

第二段试图解释一个类和它内部的嵌套类之间没有关系,除了它们的位置。

4

不,他们不冲突。请看下面的例子:

public class A { 

    public void foo() { 
     //some code 
    } 

    public class B { 

     public void bar() { 
       foo(); 
     } 
    } 
} 

在这个例子中,内部类B可以访问的A方法(或任何其领域,实际上),但绝不做继承发生。

例如,以下更改B将导致编译错误:

public class B { 

    public void bar() { 
      super.foo(); 
    } 
} 

因为B不从A继承。它可以访问其实例成员,但它确实延长(继承)。

+0

谢谢,现在完全清楚! :) – Lebowski