Subclasses do not get constructors for the parent class, but the initialization code of the parent class constructor can be invoked in the subclass constructor.
Class creature
{public
creature ()
{
System.out.println ("Creature constructor without parameters");
}
Class Animal extends creature
{public
Animal (String name)
{
System.out.println ("Animal constructor with one parameter" + "The name of the animal is" +name ";
}
Public Animal (String name,int age)
{
//Use this to invoke an overloaded constructor this
(name);
System.out.println ("Animal is a constructor with two parameters," + "has an age of +age);
}
public class Wolf extends Animal {public
wolf ()
{
///explicit invocation of the parent class has two parameters of the constructor
super ("Gray Wolf", 3);
System.out.println ("Wolf no Parameter Builder");
}
public static void Main (string[] args)
{
new Wolf ();
}
}
The results of the implementation are as follows:
Creature constructor with no parameters
Animal a constructor with a parameter, the name of the animal is grey wolf
Animal a constructor with two parameters with an age of 3
Wolf's constructor without parameters
The subclass constructor calls the parent class constructor into several situations.
The first line of the > Subclass constructor body uses super to call the parent class constructor explicitly, and the parent class object's constructor is invoked according to the incoming instance argument list in the super call
The first line of the > Subclass constructor Executor uses this to explicitly invoke the overloaded constructor in the class, and the system will call another constructor in this class based on the list of instance arguments passed in. The parent class constructor is invoked when another constructor in this class is executed.
The > Subclass constructor body has neither a super call nor this call, and the system will implicitly call the parent class parameterless constructor before executing the subclass constructor.
Regardless of the situation above, when a subclass constructor is invoked to initialize a subclass object, the parent class constructor is always executed before the constructor of that type.