Link to home
Start Free TrialLog in
Avatar of amcandrew
amcandrew

asked on

Inner classes

I am getting "<identifier> expected" and "cannot resolve symbol" messages from the compiler on line 18 (System.out.println) below. The code is meant to allow me to test some of the rules of inner classes inside of a method. Thanks for the help.

class Outer {

int x, y, z;


public Outer (int a, int b)  {
  x = a;
  y = b;
}

void prod () {

  z = x*y;

  class Inner {    
     System.out.println("x = " + z);
  }

}

}
Avatar of tsachi
tsachi

the inner class should be outside of the method prod().
it's a new class inner to this class but it's not related to the method in any way.
you can still use it in the method but in a different way
void prod()
{
z=x*y;
Inner i = new Inner();
i.print();
}

class Inner{
  void print()
  {
     System.out.println("x="+z);
  }
}
ASKER CERTIFIED SOLUTION
Avatar of Peter Kwan
Peter Kwan
Flag of Hong Kong image

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 amcandrew

ASKER

Thanks to Taschi for his answer.

 I rejected it because the purpose of my code was to test inner classes inside of a method and the solution he proved, which worked, involved a member inner class, i.e. positioned directly below the enclosing class. The second answer provided by pkwan better addressed my objective.

Alec McAndrew

Thanks for the answer.

I do have one additional question, though. The code you suggested compiles fine, which surprised me a bit. I understood from books I am reading that references to variables made inside of "local" inner classes, i.e. inner classes that are inside of a method, need to be references to final variables. In this case, method1() refers to z, which is an instance variable of Outer and is not final. Why doesn't this cause a problem?