Code to demo that a subclass invokes its superclass constructor without directly calling it.
Output
Creating an instance of ChildClass
--- Running the ParentClass constructor ---
--- Running the ChildClass constructor ---
The instance variable from the ParentClass says "Hello from the ParentClass"
The instance variable from the ChildClass says "Hello from the ChildClass"
Source Code
public class ExtendTest
{
public static void main(String [] args)
{
System.out.println("Creating an instance of ChildClass");
ChildClass tempCC = new ChildClass();
System.out.println("The instance variable from the ParentClass says \"" + tempCC.pcString + "\"");
System.out.println("The instance variable from the ChildClass says \"" + tempCC.ccString + "\"");
}
} // End of class ExtendTest
public class ChildClass extends ParentClass
{
protected String ccString;
public ChildClass()
{
System.out.println("--- Running the ChildClass constructor ---");
ccString = "Hello from the ChildClass";
}
} // End of class ChildClass
public class ParentClass
{
protected String pcString;
public ParentClass()
{
System.out.println("--- Running the ParentClass constructor ---");
pcString = "Hello from the ParentClass";
}
} // End of class ParentClass
No comments:
Post a Comment