If I have the following class:
public class TestObject {
public String Hooray() {
return \"Hooray!\";
}
}
I can obviously instantiate t
You have this:
public class TestObject {
public String Hooray() {
return "Hooray!";
}
}
TestObject a = new TestObject() {
public String Boo() {
return "Booooo";
}
}
System.out.println(a.Boo());
You can't do this. You can create new methods in anonymous inner classes, and, in fact, you are. But you wouldn't be able to call a.Boo()
from outside, since a
is a TestObject
and TestObject
has no method named Boo
. It's the same reason you can't do this:
public class Base {
public void something ();
}
public class Derived extends Base {
public void another ();
}
Base b = new Derived();
b.another(); // b is a Base, it must be cast to a Derived to call another().
In the above you have to cast b
to a Derived
to call the new method added to the derived class:
((Derived)b).another();
The reason that you couldn't do this with anonymous inner classes (which are just syntactic shortcuts for deriving new subclasses) is precisely because they are anonymous - there is no type available for you to cast them to.
The reason you can't access another()
through type Base
, by the way, is pretty simple when you think about it. While Derived
is a Base
, the compiler has no way of knowing that Base b
is holding a Derived
as opposed to some other subclass of Base
that doesn't have an another()
method.
Hope that helps.