Bookmark Topic Watch Topic
  • New Topic

Doubt in Innerclasses  RSS feed

 
vatsalya rao
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Report post to moderator
class A {
protected class InnerA
{
public InnerA()
{
System.out.println("A.InnerA()");
}

public void f()
{
System.out.println("A.InnerA.f()");
}
}//innerA end

private InnerA y = new InnerA();

public A()
{
System.out.println("New A()");
}

public void insertYolk(InnerA yy)
{
y = yy;
}

public void g()
{
y.f();
}
}//class A ending

class B extends A
{
public class InnerB extends A.InnerA
{
public InnerB()
{
System.out.println("B.InnerB()");
}

public void f()
{
System.out.println("B.InnerB.f()");
}
}//Inner B ending

public B()
{
insertYolk(new InnerB());
}

}//class B ending

public class MainClass
{
public static void main(String[] args)
{
A e2 = new B();
e2.g();
}
}//end of mainClass


I expected o/p as

newA()
B.innerB()
A.innerA.f()

because when "A e2 = new B()" is executed

the constructor A() is executed first, printing
"new A()"

then B() is called,which creates an instance of 'Inner B" thus printing

"B.inner B()"

Coming to second statement in "main" when it executes "e2.g"

g() in A is called,which inturn calls the method "f()" on innerclassA instance and printing

A.InnerA.f()



But the actual o/p is

A.InnerA()
New A()
A.InnerA()
B.InnerB()
B.InnerB.f()


Can anybody please explain this program's flow?
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Report post to moderator
Double thread.

See here:
http://www.coderanch.com/t/265814/java-programmer-SCJP/certification/Innerclasses
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
    Bookmark Topic Watch Topic
  • New Topic
Boost this thread!