user
user

Reputation: 6947

What is this syntax called? `new Type() { ... }`

I know that Java will let you do trickery with a variable's type when initializing a class variable. Along the lines of:

SomeType foo = new SomeType() {
    {
        this.fooField = 12345;
    }
    @Override public void someMethod() {
        throw new ReallyWeirdException();
    }
};

which will create an instance variable foo where someMethod() has different semantics than in the usual SomeType, and where fooField is initialized to a value other than its normal default.

But what is the new Type() { ... } syntax called?

Upvotes: 2

Views: 144

Answers (6)

Francisco Puga
Francisco Puga

Reputation: 25178

I think that the term you are looking for is anonymous classes.

Upvotes: 2

jeha
jeha

Reputation: 10750

You have

  1. a anonymous class (new SomeType() { ... }) and
  2. a initializer block (for fooField).

Upvotes: 2

DNA
DNA

Reputation: 42617

I'd call this an anonymous (sub)class.

Note that you are doing two things here - over-riding someMethod in your anonymous subclass, and also adding an instance initializer (which is setting fooField to a new value)

Upvotes: 0

ibid
ibid

Reputation: 3902

It's called an anonymous class declaration, see the spec.

Upvotes: 2

Qwerky
Qwerky

Reputation: 18455

Defining a class inside a method is a type of inner class; see http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html

Upvotes: 0

solendil
solendil

Reputation: 8458

Anonymous Inner Class.

You define a class (class) inside your code (inner) that has no name (anonymous) but inherits from SomeType, then override some of its methods and properties.

Upvotes: 3

Related Questions