Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Doubt in Innerclasses

 
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
Double thread.

See here:
https://coderanch.com/t/265814/java-programmer-SCJP/certification/Innerclasses
 
    Bookmark Topic Watch Topic
  • New Topic