是否有与嵌套类关联的构造函数 [英] Is there a constructor associated with nested classes

查看:91
本文介绍了是否有与嵌套类关联的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道内部类是否涉及任何构造函数。例如,考虑下面给出的代码段

I want to know if there are any constructors involved with inner classes. for example consider the code snippet given below

class MyOuter
{
   private int x= 10;

   class MyInner
   {
      void dostuff(){
         System.out.println("The value of x is "+x);
      }
   }
}

在另一个Java文件中,我创建了MyOuter和MyInner类的实例,如下所示

In another java file i create instances for both MyOuter and MyInner classes as shown below

Class Program
{
   public static void main(String [] args)
   {
      MyOuter mo = new MyOuter();
      MyOuter.MyInner mi = mo.new MyInner();
      mi.dostuff();
   }
}

上面的代码段可以正常编译,并输出 x的值为10。

The above code snippet compiles fine and gives output of "The value of x is 10".

在这里我想知道的是,当将new()与MyInner类和MyOuter类一起使用时,是否调用了构造函数。如果是,那么是否有从内部类到外部类的构造函数链接(例如子类调用超类的构造函数等等)。

What i want to know here is whether a constructor is invoked when new() is used with MyInner class and MyOuter class. If yes, then is there any constructor chaining from inner class to outer class (like subclass calls constructor of super class and so on).

推荐答案

扩展内部类时,可以观察到内部类的构造函数链。

You can observe the constructor chain for the inner class when you extend an inner class.

以该示例为例:

public class MainClass {

    public MainClass(String value) {
        System.out.println("mainValue: " + value);
    }

    public class NestedClass {

        public NestedClass(String nestedValue) {
            System.out.println("nestedValue: " + nestedValue);
        }
    }

}

像这样扩展NestedClass

and then extend the NestedClass like this

public class NestedClassExtension extends NestedClass {

    public NestedClassExtension(MainClass mainClass, String nestedValue) {
        mainClass.super(nestedValue);
    }
}

所以您可以看到嵌套类的超级构造函数传递给该构造函数 MainClass ,并在上调用 .super mainClass 对象实例。

so you can see that you are able to call the super constructor of your nested class passing to that constructor the MainClass, and calling .super on mainClass object instance.

现在您可以通过以下方式创建NestedClassExtension实例:

Now you can create NestedClassExtension instances in this way:

NestedClassExtension extension = new NestedClassExtension(new MainClass("main"), "nested");

因此主类必须存在,其构造函数首先被调用。然后是嵌套类的构造函数。

So the main class has to exist, and its constructor it is called first. Then the constructors of the nested classes.

相反,如果要在 MainClass NestedClass 实例$ c>您必须编写:

Instead if you want create a NestedClass instance outside of the MainClass you have to write:

MainClass mc = new MainClass("main");
mc.new NestedClass("nested");

另一次,必须将 MainClass 设为首先创建,然后再创建嵌套的类。

Another time, the MainClass has to be created first, then the nested classes.

这篇关于是否有与嵌套类关联的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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