简体   繁体   English

实例化类的内部类

[英]Instantiating inner class of class

Basically I have a java class Foo with a generic T and a inner class Foo2 which is using this generic T somehow like the following example: 基本上,我有一个带有通用T的Java类Foo和一个内部类Foo2,该类以某种方式使用了此通用T,例如以下示例:

public class Foo<T>
{
  public class Foo2
  {
    private T t;
    public void setObject(T t)
    {
       this.t = t;
    }
  }
}

After try and error (until the compiler don't throw a warning or error) how to create an instance of this inner class Foo2 I came up with the following: 在尝试并出错(直到编译器不会引发警告或错误)之后,如何创建此内部类Foo2的实例,我想到了以下内容:

Foo<String> foo = new Foo<String>();
Foo2 foo2 = foo.new Foo2();

The second line foo.new Foo2(); 第二行foo.new Foo2(); is something which is new for me and I don't know what exactly I'm doing here. 对我来说是新事物,我不知道我在这里到底在做什么。 For me it is somehow clear, that an instance of the class Foo2 has to know what class T is but the syntax foo.new is new for me. 对于我来说,很明显,类Foo2的实例必须知道T是什么类,但是语法foo.new对我来说是新的。 What am I doing here? 我在这是要干嘛?

The foo.new Foo2() syntax has nothing to do with generics. foo.new Foo2()语法与泛型无关。 It's a way to instantiate an inner class by supplying an instance of the enclosing class. 这是通过提供封闭类的实例来实例化内部类的方法。

An inner class is a class declared inside another one without using the static keyword. 内部类是在另一个内部声明的类,不使用static关键字。 An instance of an inner class has to belong to an instance of the outer class. 内部类的实例必须属于外部类的实例。 For example, a good example of an inner class might be 例如,内部类的一个很好的例子可能是

public class School {

    public class Pupil {

    }
}

Every Pupil has to belong to a School so you cannot construct a Pupil instance without a school. 每个Pupil都必须属于School因此如果没有School ,您将无法构建Pupil实例。 You can do 你可以做

School school = new School();
School.Pupil pupil = school.new Pupil();

The second line creates a new Pupil belonging to a particular School . 第二行创建一个属于特定School的新Pupil

Inside the Pupil class you get the school the pupil belongs to by doing School.this . Pupil课堂上,通过School.this可以得到学生所属的学校。 You can use fields of the School class by doing School.this.someField . 您可以通过执行School.this.someField来使用School类的School.this.someField

If you want to be able to create Foo2 instances without an instance of Foo you can write 如果您希望能够在没有Foo实例的情况下创建Foo2实例,则可以编写

public static class Foo2

instead. 代替。 In most cases, you probably should use static nested classes in preference to inner classes. 在大多数情况下,您可能应该优先使用静态嵌套类而不是内部类。

Inner classes (as opposed to static inner classes) are associated with a particular instance of the outer class. 内部类(与静态内部类相对)与外部类的特定实例相关联。

foo.new associates the new instance of the inner class with the instacne of the outer class from the foo variable. foo.new通过foo变量将内部类的新实例与外部类的foo.new关联。

This has nothing to do with generics. 这与泛型无关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM