java - Parent constructor taking Parent Object as a parameter -


i have code:

public class parent  {     int num;     parent p;      parent()     {      }      parent(parent s)     {         p=s;     }      void print()     {         system.out.println(p.num);     }  } 

and:

public class child  {      public static void main(string args[])     {         parent p1=new parent();         parent p2=new parent(p1);         parent p3=new parent(p2);         p2.num=5;//line 1         p2.print();//line 2          } } 

the o/p 0. true when replace line 1 , 2 p3.num=5 , p3.print() respectively. when replace p1.num=5 , p1.print(), runtime error (nullpointerexception). can explain behavior?

that very strange class. print method of instance prints num associated p passed constructor. have 2 constructors, 1 of doesn't ever set p, means p null if use constructor; other constructor remembers parent give assigning p.

so:

  • calling p1.print() fail because p1's p null, trying use p.num throws npe.

  • calling p2.print() show p1's num, 0 because never set , default value data members "all zeroes" value, 0 int.

  • calling p3.print() show p2's num, (in original code) 5, because that's set before calling p3.print().

the reason it's strange class instances have num data member, print doesn't print their num, prints num of parent passed in (if any).


Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -