Link to home
Start Free TrialLog in
Avatar of stsanz
stsanz

asked on

Cannot refer to a non-final variable inside an inner class

I have to get an object from an inner class method :

  Object  myObject ;
            
  GetObject(objectKey,new ResultReader () {
    public boolean Read (Collection data) {
      myObject = GetObjectFromCollection(data) ;
    }
  ) ;

  // Now use myObject
  String s = myObject.toString() ;
  // ...

The ResultReader class is an interface, for which the Read method is called by the
'GetObject' method when it passes the object bakc to the caller :

  public interface ResultReader {
    public boolean Read(Collection data);
  }

The problem is that such a code generates an error message at compilation :
"Cannot refer to a non-final variable 'myObject' inside an inner class defined in a different method"
at the line containing "myObject = GetObjectFromCollection(data) ;"


A way to bypass this limitation I have been using is to store the object I get into a Vector defined as 'final',
but I found the solution quite inelegant :

  Object myObject ;
            
  final  Vector v = new Vector() ;

  GetObject(objectKey,new ResultReader () {
    public boolean Read (Collection data) {
      Object myTempObject = GetObjectFromCollection(data) ;
      v.add(myTempObject) ;
    }
  ) ;

  // Get the object back from the Vector
  myObject = v.get(0) ;

  // Now use myObject
  String s = myObject.toString() ;
  // ...

Do you know any other solution that would be more elegant : define the inner class in another manner? declare the object I have to retrieve in some special way?

And why is there such a limitation with the use of inner classes ?

Thanks for answers.

ASKER CERTIFIED SOLUTION
Avatar of Venci75
Venci75

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of kumvjuec
kumvjuec

I don't quite understand your getObject(), is this how it looks in your code? or you're trying to show how it works?

From what is written in getObject(), you are using anonymous class but still an inner class type.

Here is an example to show you that myObject can be assgned within inner class:

public interface Inner{
  public void getObject();
}

class InnerClass{

Object myObject;

void myToString(){
  // Anonymous class with its method call
  (new Inner(){
   public void getObject(){
     myObject = new Object();
   }
  }).getObject();
  System.out.println(myObject.toString());
}

public static void main(String[] args){
  new InnerClass().myToString();  
}


Is this what you're trying to do?
}
this is incomprehensible