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 becausep1
'sp
null
, trying usep.num
throws npe.calling
p2.print()
showp1
'snum
,0
because never set , default value data members "all zeroes" value,0
int
.calling
p3.print()
showp2
'snum
, (in original code)5
, because that's set before callingp3.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
Post a Comment