Semaphor
Semaphor

Reputation: 1040

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:

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:

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

The second line 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. What am I doing here?

Upvotes: 3

Views: 1511

Answers (3)

Paul Boddington
Paul Boddington

Reputation: 37645

An inner class is a class declared inside another one without using the static keyword. 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. 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.

Inside the Pupil class you get the school the pupil belongs to by doing School.this. You can use fields of the School class by doing School.this.someField.

If you want to be able to create Foo2 instances without an instance of Foo you can write

public static class Foo2

instead. In most cases, you probably should use static nested classes in preference to inner classes.

Upvotes: 4

Eran
Eran

Reputation: 393781

The foo.new Foo2() syntax has nothing to do with generics. It's a way to instantiate an inner class by supplying an instance of the enclosing class.

Upvotes: 3

SLaks
SLaks

Reputation: 887285

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.

This has nothing to do with generics.

Upvotes: 1

Related Questions