Re: Anonymous class - I don't know how to...
- From: Andreas Leitgeb <avl@xxxxxxxxxxxxxxxxxxxxxxxx>
- Date: 28 Jun 2007 19:40:35 GMT
kaja_love160@xxxxxxxxx <kaja_love160@xxxxxxxxx> wrote:
hello
1) Syntax for creating anonymous class:
new < superclass> ( <params> ) { <class definition> };
Example:
Object o = new Object() { public int anon = 20; };
The above statement creates an object of anonymous class and returns
a reference to it. But in order to use members declared in anonymous
class ( o.anon ), ...
.... you'd not only define the variable, but also overwrite
a (non-final, of course) method from the base-class, which then
accesses the variable.
e.g.
Object o = new Object() {
public int anon = 20;
// doesn't make much sense except for the sake of an example:
public String toString() { anon++; return Integer.toString(anon); }
}
o.toString(); // -> 21
o.toString(); // -> 22
Alternatively, you can also use the reflection-API to
see and access the variable "anon" of the object referenced by "o".
2)
If we declare class C inside method A(), then any local variable
( declared inside A() ) that will also be used inside class C, must be
declared final. Why? I assume there must be some valid reason for
that?
public void A ( final int i ) {
class C { int u = i ; }
}
The reasons are perhaps more technical than anything else.
At class-file level, C is in a separate class-file than the
class containing A, and it would be quite complicated to implement
a connection between C's "i", and the local variable "i" in A.
The same restriction holds currently, if "i" were a field of the
class that contains "A", and my feeling is, that this case is
slightly more likely to change in future than the case of a local
variable.
In a nutshell, I consider it a current limitation of implementation
that was then taken into java language spec for practical reasons.
I wouldn't bet that this requirement will be there into all eternity.
At some point in future, some brilliant programmer might find a way
to actually implement a live connection between these vars, despite
the current fundamental difference between local variables and class
variables, and the requirement for "final" might then be dropped.
PS: I'm sure, some will followup with their personal decision, that
they indeed would bet on this limitation never ever changing, and
I wouldn't bet against them, either. I'm not really the betting
type :-)
.
- Follow-Ups:
- Re: Anonymous class - I don't know how to...
- From: Patricia Shanahan
- Re: Anonymous class - I don't know how to...
- From: Twisted
- Re: Anonymous class - I don't know how to...
- References:
- Anonymous class - I don't know how to...
- From: kaja_love160
- Anonymous class - I don't know how to...
- Prev by Date: Re: ClassNotFoundException inside jar
- Next by Date: Re: ClassNotFoundException inside jar
- Previous by thread: Anonymous class - I don't know how to...
- Next by thread: Re: Anonymous class - I don't know how to...
- Index(es):
Relevant Pages
|