Hi!
While developing the class for Account Holder. I am trying to contain an object of Date class inside the Account Holder object. the Code is as follows:
class Date
{
private int dd,mm,yy;
public Date()
{
dd = mm = yy=1;
}
public Date(int d,int m,int y)
{
dd = d;
mm = m;
yy = y;
}
public String toString()
{
return dd+"/"+mm+"/"+yy;
}
public void disp()
{
System.out.println(dd+"/"+mm+"/"+yy);
}
}
class AccHolder
{
int emp_id;
String name;
Date jng_dt;
float sal;
public AccHolder()
{
}
public AccHolder(int i,String n, Date j,float s)
{
emp_id = i;
name = n;
jng_dt = j;
sal = s;
}
public String toString()
{
return emp_id+"/n"+name+"/n"+jng_dt+"/n"+sal;
}
public void disp()
{
System.out.println(emp_id+"/n"+name+"/n"+jng_dt+"/n"+sal);
}
public void disp1()
{
System.out.println(emp_id+"/n"+name+"/n"+sal);
jng_dt.disp();
}
public static void main(String[] args)
{
AccHolder a1 = new AccHolder();
System.out.println(a1);
/* for a1.jng_dt is displayed as null */
AccHolder a2 = new AccHolder();
a2.disp();
/* for a2.jng_dt is displayed as null */
AccHolder a3 = new AccHolder();
a3.disp1();
/* Runtime exception thrown for jng_dt as it is null*/
}
}
If it is said that when we pass Object directly to the System.out.println(). Then internally toString for that Object is called which is a method call. Then why disp() of date generates Exception @ runtime. also if we explicitly call toString() of Date as (jng_dt.toString()) in disp() of Account Holder runtime exception is generated.
Can u help me out for this ? I cannot understand this problem.
thanx,
meghana