Most examples of anonymous classes in Java use interfaces but it is also possible to create an anonymous class by overloading a normal class. Here is an example:
class inner
{
int x;
inner (int x) { this.x = x; }
int next () { return x + 1; }
public static void main (String[] args)
{
inner i = new inner (42);
inner j = new inner (42) {
{ this.x = x + 1; }
int next () { return x - 1; }
};
System.out.println (i + ": " + i.x); System.out.println (j + ": " + j.x);
System.out.println (i + " next: " + i.next()); System.out.println (j + " next: " + j.next()); }
}
And here is a bit more complicated example: an anonymous class derived from an abstract class implementing an interface based on another interface.
class run
{
interface Named
{
String name ();
}
interface Column<T> extends Named
{
T get ();
void set (T value);
}
abstract class StringColumn implements Column<String>
{
public abstract String name ();
int length;
StringColumn (int length) { this.length = length; }
String value;
public String get () { return value; }
public void set (String value) { this.value = value; }
}
run ()
{
Column<String> column = new StringColumn (100) {
public String name () { return "FIRSTNAME"; }
};
column.set ("Sascha");
System.out.println (column.name() + ": " + column.get());
}
public static void main (String[] args)
{
new run (); }
}
Keine Kommentare:
Kommentar veröffentlichen