How to access inner classes variables & methods from outer classes

L

lonelyplanet999

Hi,

I have below code defining 1 outer class enclosing 2 inner classes.

If I want to access or display members of MyInner class from MyOuter
class methods (the same applied to accessing NewInner members from
MyInner class methods or MyOuter class methods), is creating instances
of MyInner (or NewInner) class within MyOuter class the only way to
achieve the goal ?


class P461 {
public static void main (String [] args) {
MyOuter mo = new MyOuter();

MyOuter.MyInner inner = mo.new MyInner();
System.out.println("inner\n=====");
inner.seeOuter();
inner.see2Outer();

MyOuter.MyInner.NewInner xinner = mo. new MyInner(). new
NewInner();
MyOuter.MyInner.NewInner ninner = inner.new NewInner();
System.out.println("xinner\n======");
xinner.seeOuter();
System.out.println("ninner\n======");
ninner.seeOuter();
}
}

class MyOuter {
private int x=7;
private int y=-1;
public void makeInner() {
MyInner in = new MyInner();
in.seeOuter();
}
public int gety() { return y; }

class MyInner {
private int y=-2;
public void seeOuter() {
System.out.println("Outer x is "+x);
}
public void see2Outer() {
System.out.println(this+".see2Outer");
System.out.println("Default y is "+y);
System.out.println("Outer y is "+MyOuter.this.y);
System.out.println("Outer gety() is "+MyOuter.this.gety());
}

class NewInner {
private int x=777;
private int y=-3;
public void seeOuter() {
System.out.println("NewInner x is "+x);
}
}
}
}
 
V

VisionSet

lonelyplanet999 said:
Hi,

I have below code defining 1 outer class enclosing 2 inner classes.

If I want to access or display members of MyInner class from MyOuter
class methods (the same applied to accessing NewInner members from
MyInner class methods or MyOuter class methods), is creating instances
of MyInner (or NewInner) class within MyOuter class the only way to
achieve the goal ?
....

Yes, as with any instance attribute of any class, you must have an instance
to go with it, it only exists when you create an instance.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top