Java compiler complains when you write a code that is unreachable. For example
public void go()
{
return;
System.out.println("unreachable");
}
However, when you define a new method in an anonymous class which cannot be reached from anywhere, compiler does not complain. It allows you to do that, why? For example,
class A
{
public void go()
{
System.out.println("reachable - A");
}
}
class B
{
public static void main(String [] args)
{
A a = new A() {
public void go()
{
System.out.println("reachable - B");
}
public void foo()
{
System.out.println("unreachable - B");
}
};
a.go(); // valid
a.foo(); // invalid, compiler error
}
}
First of all: Eclipse does notify my that foo()
is never used locally. It's a warning and not an error, however, for reasons pointed out by the other anserws.
Note that there is a way to reach foo()
:
new A() {
public void go()
{
System.out.println("reachable - B");
}
public void foo()
{
System.out.println("unreachable - B");
}
}.foo();
This works, because the type of the expression new A() {}
is not A
, but actually the anonymous subclass of A
. And that subclass has a public foo
method.
Since you can't have a variable with the same type, you can't access foo()
this way from a variable.