Java:非静态嵌套类和instance.super() [英] Java: Non-static nested classes and instance.super()

查看:124
本文介绍了Java:非静态嵌套类和instance.super()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难用Java包围非静态嵌套类。考虑以下示例,其中打印内部然后打印子。

I'm having a hard time wrapping my head around non-static nested classes in Java. Consider the following example, which prints "Inner" and then "Child".

class Outer {
    class Inner {
        Inner() { System.out.println("Inner"); }
    }
}

public class Child extends Outer.Inner {
    Child(Outer o) {
        o.super();
        System.out.println("Child");
    }
    public static void main(String args[]) {
        new Child(new Outer());
    }
}

我知道Inner的实例总是必须关联有一个外部实例,这也适用于Child,因为它扩展了Inner。我的问题是 o.super()语法是什么意思 - 为什么它会调用Inner构造函数?

I understand that instances of Inner always have to be associated with an Outer instance, and that that applies to Child too since it extends Inner. My question is what the o.super() syntax means - why does it call the Inner constructor?

I我们只看到一个普通的 super(args)用来调用超类构造函数而 super.method()来调用重写方法的超类版本,但从不以 instance.super()的形式出现。

I've only seen a plain super(args) used to call the superclass constructor and super.method() to call the superclass version of an overridden method, but never something of the form instance.super().

推荐答案

它被称为合格的超类构造函数调用。

It's called a "qualified superclass constructor invocation".

引自这里


显式构造函数调用语句可分为两种:

Explicit constructor invocation statements can be divided into two kinds:


  • 替代构造函数调用以关键字this开头(可能以显式类型参数开头)。它们用于调用同一类的备用构造函数。

  • Alternate constructor invocations begin with the keyword this (possibly prefaced with explicit type arguments). They are used to invoke an alternate constructor of the same class.

超类构造函数调用以关键字super(可能以显式类型参数开头)或者主要表达。它们用于调用直接超类的构造函数。超类构造函数调用可以进一步细分:

Superclass constructor invocations begin with either the keyword super (possibly prefaced with explicit type arguments) or a Primary expression. They are used to invoke a constructor of the direct superclass. Superclass constructor invocations may be further subdivided:



  • 非限定超类构造函数调用以关键字super开头(可能以显式类型参数开头)。

  • Unqualified superclass constructor invocations begin with the keyword super (possibly prefaced with explicit type arguments).

合格的超类构造函数调用以Primary表达式开头。它们允许子类构造函数显式指定新创建的对象关于直接超类(第8.1.3节)的直接封闭实例。当超类是内部类时,这可能是必要的。

Qualified superclass constructor invocations begin with a Primary expression . They allow a subclass constructor to explicitly specify the newly created object's immediately enclosing instance with respect to the direct superclass (§8.1.3). This may be necessary when the superclass is an inner class.


这篇关于Java:非静态嵌套类和instance.super()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆