Hi people,
I've a question about scope in java, somebody can help me?
How can access 's' variable in code below?
thanks a lot.
public class TopClass
{
protected String s;
public TopClass()
{
AnyClass anyclass = new AnyClass() {
//methodThatINeedToImplement is abstract method from
AnyClass
void methodThatINeedToImplement()
{
//how can I acess 's' variable here?
}
}
}
This is the kind of test that's easy for you to check yourself as it pretty
much compiles as-is. Much more fun and educational than asking for answer.
It works because the scope of an inner class includes the outer class.
Every inner class includes a reference to the enclosing outer class. Your
new class, which is an anonymous inner subclass of AnyClass, will have
access to TopClass's instance variables, including s, as well as its
methods. It makes no difference whether AnyClass is a real class or an
abstract class or an interface or whether it has concrete or abstract
methods--only that it's an inner class.
The following compiles and runs just fine. I've changed the protection of s
to private from protected to show that it is within class scope and I've
extended the code so that it's clear that the inner class can incorporate s
before s has a value and that the value of s may change. (This isn't
necessarily good style--it's just to show how it works.)
public class TopClass {
private String s;
private AnyClass anyclass;
public TopClass() {
anyclass = new AnyClass() {
public void methodThatINeedToImplement() {
System.out.println(s);
}
};
}
public void setS (String v) { s = v; }
public void doX () { anyclass.methodThatINeedToImplement (); }
public static final void main(String[] args) {
TopClass tc = new TopClass ();
tc.setS ("First");
tc.doX ();
tc.setS ("Second");
tc.doX ();
}
}
public abstract class AnyClass {
public abstract void methodThatINeedToImplement ();
}
Local variables present at the time the inner class is instantiated are also
in scope, but must be marked "final" so as to clarify the fact that their
references are copied to the new instance and cannot change.
Cheers,
Matt Humphrey (e-mail address removed)
http://www.iviz.com/