Here is the flow of the program:
class X
{
Y b = new Y();//2
X()
{
System.out.print("X"); //4
}
}
class Y
{
Y()
{
System.out.print("Y"); //3 & 6
}
}
public class Z extends X
{
Y y = new Y(); //5
Z()
{
System.out.print("Z"); //7
}
public static void main(String[] args)
{
new Z(); // 1 calls z class
}
}
Y is printed twice because z class & its super class x instantiate y class.
Hope this helped
Originally posted by Wasim Ahmed:
look at the following Q's. I fail to understand why "Y" is printing twice, can some expert give me "concept" behind it ?
Output is = YXYZ :confused
class X
{
Y b = new Y();
X()
{
System.out.print("X");
}
}
class Y
{
Y()
{
System.out.print("Y");
}
}
public class Z extends X
{
Y y = new Y();
Z()
{
System.out.print("Z");
}
public static void main(String[] args)
{
new Z();
}
}