views:

107

answers:

4
public class Ex7 {
    private int fld;

    private void meth(int val) {
        fld = val;
        System.out.println(" meth() -> fld = " + fld);
    }

    public class Ex7Inner1 {
        void operateOnFld() {
            fld = 12;
        }

        void operateOnMeth() {
            meth(10);
        }

        public void bar() {
            System.out.println(" bar() ");
        }
    }

    class Ex7Inner2 {
        Ex7Inner1 i1 = new Ex7Inner1();
        // how to call i1.bar() ??
        i1.bar();
    }
}
+8  A: 

Your problem is that you need to call i1.bar() inside a function. For example

class Ex7Inner2 {
    Ex7Inner1 i1 = new Ex7Inner1();  // this is now a field of the Ex7Inner2 class
    public void callBar() {
        i1.bar();                    // this will work
    }
}

In the future, you may find that people are able to be more helpful if you include the error you get in your question, which I'll do now. When you try to compile the code your way, you get an error that looks like

Ex7.java:26: <identifier> expected
  i1.bar();
        ^
1 error

This is because the only thing you can do outside of a method (like you originally had it) is declare variables. So it was expecting an "identifier" by which it meant "the name of the variable you are declaring". So if you had said

String s;

then s would have been the identifier.

Eli Courtwright
now i feel that this was a dumb question.. how could i have wrote such code?
Flueras Bogdan
Haha, I often find myself asking the same question about my own code. Don't let it get you down - you're not alone!
Eli Courtwright
A: 

A few things wrong here;

  • your inner2 needs to be calling the i1 inside of a function
  • since you didn't declare inner1 static it needs an instance of the enclosing Ex7 to exist.

So you can do something like this:

public class Ex7 {

    private Ex7Inner1 i1;
    public class Ex7Inner1 {
     public void bar() {
      System.out.println( " bar() " );
     }
    }

    class Ex7Inner2 {
     // how to call i1.bar() ??
     public Ex7Inner2() {
      Ex7.this.i1.bar();
     }
    }
}

To access the Ex7's i1.

Where your Ex7 instance contains an inner1 and an inner2 and your reference from within inner2 is inner2-->parentEx7 -->child inner1.

If you make the inner class static you can do away with the Ex7 reference, as you're defining that the inner class doesn't need an instance of the outer class to exist.

Steve B.
A: 

but there are no method in Ex7Inner2 class. create method with 'i1.bar();' call inside and it compiles ok

A: 

Ex7Inner1 needs a reference to Ex7 in order to instantiate. From Ex7Inner2 that reference is Ex7.this.

Thus say

Ex7Inner1 i1 = Ex7.this.new Ex7Inner1()

See the Java Tutorial from more information.

Kathy Van Stone