0

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?

2
  • 2
    What doesn't work? You should really post the error! Commented Dec 8, 2011 at 12:37
  • 1
    If you haven't defined AnonymousClass, it won't work! Commented Dec 8, 2011 at 12:38

5 Answers 5

4

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).

Sign up to request clarification or add additional context in comments.

3 Comments

@gustafc: anonymous classes also retain an implicit reference to the outer object. No difference with method-local classes.
As a point of pedantry, you can do it [slightly] non-directly. Pass it through a method private static <T> T fn(T value) { return value; }.
@JB Nizet - quite right, fixed the post to say what I actually meant. I'll have to blame an oncoming cold for not thinking about that.
2

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);
}

Comments

2

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.

2 Comments

It won't compile, a.whatever is not visible.
Except the print statement wouldn't work. a is of type AnonymousClass (the interface), which doesn't specify the presence of whatever.
0

You are referring original anonymous class instance, which has no field "whatever" - so you can not reference it this way.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.