Wednesday, August 1, 2007

Child Class Should do all Initialization

Hi

consider the following code... it will give compile time error


class memberClass
{
memberClass()
{
System.out.println("Member Class constructor called");
}
};

class ParentClass
{
ParentClass()
{
System.out.println("Parent Class constructor called");
}
}

public class ChildClass
{
private memberClass = new memberClass();

public ChildClass()
{
super(memberClass);
// super has to be the 1st call in the constructor ..
// cant pass it memberClass as argument : ERROR
// SOLUTION : do all initialization in Child
}

public static void main(String[] args)
{
System.out.println("Hello World!");
}
}



Error : cannot reference this before superclass constructor has been called


package try_project1;

class memberClass
{
memberClass()
{
System.out.println("Member Class constructor called");
}
};

class ParentClass
{
ParentClass( )
{
System.out.println("Parent Class constructor NO INITIALIZATION ");
}
}

public class ChildClass extends ParentClass
{
private memberClass memc= new memberClass();

public ChildClass()
{
super();
System.out.println("do ALL INITIALIZATION in child Class");
}

public static void main(String[] args)
{
System.out.println("Child Class Hello World!");
ChildClass cc = new ChildClass();
}
}

No comments: