Reputation: 1159
Is it possible to create an anonymous class in Java like this:
public static void main(String[] args) {
AnonymousClass a = new AnonymousClass() {
int whatever = 1;
};
System.out.println(a.whatever);
}
I thought that this would be working but it doesn't. Do I misunderstand something with anonymous classes or is there only a syntax error?
Upvotes: 0
Views: 420
Reputation: 28895
You can do it this way:
public static void main(String[] args) {
System.out.println(new Object() {
int whatever = 1;
}.whatever);
}
That is, you can only dereference the fields and method directly from the instantiation expression. [Edit: Per the comments, you can use it where the compiler infers the type for you - which happens to be the instantion expression, or as a return value from a generic method you pass it to.] You can't store it in a variable and use fields/methods there, so it's not as useful as anonymous classes in e.g. C#.
Edit: You can, as previously stated by others, declare a method-local class:
public static void main(String[] args) {
class Local {
int whatever = 1;
}
Local local = new Local();
System.out.println(local);
}
Slightly wordy, though, and like non-static inner classes and regular anonymous classes, it retains an implicit reference to the enclosing this
(in non-static methods).
Upvotes: 4
Reputation: 62294
For this to work, AnonymousClass needs to be an Interface or a Class:
private interface AnonymousClass {
}
public static void main(String[] args) {
AnonymousClass a = new AnonymousClass() {
int whatever = 1;
};
System.out.println(a.whatever); // this won't work
}
EDIT
Corrected, as correctly stated in the comment, whatever
won't accessible / present.
Upvotes: 2
Reputation: 797
You can create your class like this, sure. However, the a.whatever
call will fail, because the object type is still AnonymousClass
, and it does not define whatever
as an attribute.
If you overwrite some method or attribute that is already defined in the AnonymousClass
class or interface, the object will use your implementation from the anonymous class instead of the old one, but not if you introduce new methods or attributes.
Upvotes: 0
Reputation: 692161
If it was possible, we would not call them anonymous anymore: your example defines a class with a name: Anonymous
. You may define an inner class with a name like this:
public static void main(String[] args) {
class NotAnonymous {
public int whatever = 1;
}
NotAnonymous na = new NotAnonymous();
System.out.println(na.whatever);
}
Upvotes: 2
Reputation: 12367
You are referring original anonymous class instance, which has no field "whatever" - so you can not reference it this way.
Upvotes: 0