/**
* This code is edited from the book:
*
* Winder, R and Roberts, G (1998)
* Developing Java Software
* John Wiley & Sons.
*
* It is copyright (c) 1997 Russel Winder and
* Graham Roberts.
*/
interface Thing
{
void test(final String s);
}
class Subclass
{
public void doSomething()
{
System.out.println("Doing Something");
}
}
class Class10
{
// Return an object created using an anonymous class
// implementing an interface
public Thing i1()
{
Thing t = new Thing ()
{
public void test(final String s)
{
System.out.println(s);
}
}; // Note the semi-colon here
return t;
}
// Version that eliminates local variable
// implementing an interface
public Thing i2()
{
return new Thing ()
{
public void test(final String s)
{
System.out.println(s);
}
}; // Note the semi-colon here
}
// Return an object created using an anonymous class
// subclassing a class
public Subclass f1()
{
Subclass t = new Subclass()
{
public void doSomething()
{
something();
}
private void something()
{
System.out.println(name);
}
String name = "Anonymous 1";
};
return t;
}
// Version that eliminates local variable
// subclassing a class
public Subclass f2()
{
return new Subclass()
{
public void doSomething()
{
something();
}
private void something()
{
System.out.println(name);
}
String name = "Anonymous 2";
};
}
public static void main(String[] args)
{
Class10 c10 = new Class10();
Thing t1 = c10.i1();
t1.test("hello");
Thing t2 = c10.i2();
t2.test("world");
Subclass t3 = c10.f1();
t3.doSomething();
Subclass t4 = c10.f2();
t4.doSomething();
}
}
/******** sample compilation & run *******
# javac l1Anon2.java
# java l1Anon2
hello
world
Anonymous 1
Anonymous 2
#
******************************************/