Java中的内部类构造 [英] Inner class construction in Java

查看:169
本文介绍了Java中的内部类构造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读过 类别 ,然后出现以下代码为何无效的问题?

I've read about class fromal parameters and the question then arises as to why the following code is ill-formed?

class A

package org.gradle;

public class A extends B.Inner{

    public A(B s){
        s.super(new B()); //error
        s.super();        //OK
    }
}

class B

package org.gradle;

public class B{

    public class Inner{
    }
}

所说内容的关键部分是:

The key part of what was said is:


私人内部成员类隐式
声明一个代表
直接包含类

The constructor of a non-private inner member class implicitly declares, as the first formal parameter, a variable representing the immediately enclosing instance of the class

所以,我希望除了默认构造函数,我们应该有一个具有以下签名的构造函数:

So, I expect that besides the default constructor, we should have a constructor with the following signature:

Inner(B b);

为什么不?

推荐答案

extra参数实际上被隐藏了 - 无论是声明它还是执行它。当你执行它,你提供一个不同的方式 - 在你的情况下,通过 s

The "extra" parameter is effectively hidden from you - both when you declare it, and when you execute it. When you execute it, you provide a value in a different way - in your case, via s:

s.super();

这是通过 s 作为隐藏的额外参数到 B.Inner 构造函数。所有这一切的语法有点怪异 - 我个人试图避免使用内部类在这种情况下...他们只是变得很奇怪很快。我通常喜欢静态嵌套类,如果我需要一个内部类,它几乎总是私有的。将在不同顶级类中声明的内部类进行子类化是一种奇怪的情况,IMO。

That's passing s as the hidden extra argument to the B.Inner constructor. The syntax for all of this is a little weird - and I would personally try to avoid using inner classes in this sort of situation... they just get weird very quickly. I usually prefer static nested classes, and if I do need an inner class, it's almost always private. Subclassing an inner class declared in a different top-level class is an odd situation, IMO.

这篇关于Java中的内部类构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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