-5

If i have a Inner class (not static) example:

public class A {
     int myNumber = 100;

     class B {
     }  

     public static void main(String[] args) {
         A outerObj = new A();
         B innerObj = outerObj.new B();
         System.out.println("i want the access to the variable 
                             myNumber by the innerObject"); 

     }
}

i mean: i would like with the innerObject to reach the outerObject and see the variable myNumber. I can do that just if i'm in a method of the B Class... but i would like everywhere to see the variabile of the outerObj by the inner.... it's possible? if not why?
thanks

Giovanni Far
  • 1,623
  • 6
  • 23
  • 37

1 Answers1

1

I assume that you want something like this:

class B
{
   private int getNum()
   {
      return myNumber;
   }

   private void setNum(int x)
   {
      myNumber = x;
   }
}

However, you cannot get access to myNumber from an instance of B, b, by doing b.myNumber. Here's why.

Community
  • 1
  • 1
Steve P.
  • 14,489
  • 8
  • 42
  • 72
  • yes thi i know, but i dont want enter in the class b to read the variables of the outer obj... i would to read them directly in the main method or in other method but not of the class b – Giovanni Far Dec 07 '13 at 21:49
  • @GiovanniFar Then you could just read from class A? What you're saying doesn't make sense to me. You want to read the members of A without A, but with a nested class that can only be initialized by A? But you don't want to use methods? Why? If so, you need to access from A. – Steve P. Dec 07 '13 at 21:50
  • No i mean this: my innerObj points to the outer Obj ok ? there is a way with the innerObj to see the variabiles of the outerObject WITOUHT using the class b so WITHOUT using the class of the innerobj? i would like to know if the innerobj i can see the variable of the outerobj everywhere or just in the class b and why – Giovanni Far Dec 07 '13 at 21:58
  • @GiovanniFar Just in class `B`, [here's](http://stackoverflow.com/questions/13700138/accessing-outer-class-variable-via-inner-class-object-in-main) why. – Steve P. Dec 07 '13 at 22:07