File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes anonymous class example Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "anonymous class example" Watch "anonymous class example" New topic

anonymous class example

Suman Sharma
Ranch Hand

Joined: May 16, 2005
Posts: 72
In the following example, the line: AbstractTest.MyInner minn = new AbstractTest().MyInner() is giving error. It expects ; at the end of this line, but I am trying to instantiate it anonymously and get the value of minn.num. Can anyone explain me how it can be fixed?

Thank you.
marc weber

Joined: Aug 31, 2004
Posts: 11343

The compiler is expecting the word "new" before the inner instance...

AbstractTest.MyInner minn = new AbstractTest().new MyInner() {...

However, once that is fixed, you will see that abstract classes (like AbstractTest) cannot be instantiated.

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
Suman Sharma
Ranch Hand

Joined: May 16, 2005
Posts: 72
Thank you.
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199


AbstractTest.MyInner minn = MyInner();

is what you're looking for?

But besides this, I see that your classes are written as if you expect variables to behave polymorphically -- they do not. You should never redefine a variable in a subclass like this. If the variable needs to have a different value in a subclass, then assign a different value in the constructor of the subclass (or in an anonymous class, in an initialization block). But never try to "override" a variable -- you'll just get weird, hard to understand results.

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link:
subject: anonymous class example
It's not a secret anymore!