Reputation: 6947
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
Reputation: 25178
I think that the term you are looking for is anonymous classes.
Upvotes: 2
Reputation: 10750
You have
new SomeType() { ... }
) and fooField
).Upvotes: 2
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
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
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