1. Hands-On Labs: Construction method invocation under inherited conditions
Source:
Class grandparent
{
Public grandparent ()
{
System.out.println ("Grandparent Created.");
}
Public grandparent (String string)
{
System.out.println ("Grandparent created.string:" +string);
}
}
Class Parent extends grandparent
{
Public Parent ()
{
Super ("hello.grandparent.");
System.out.println ("Parent Created");
Super ("hello.grandparent.");
}
}
Class Child extends parent{
Public Child ()
{
System.out.println ("Child Created");
}
}
public class Testinherits {
public static void Main (string[] args) {
TODO auto-generated method stubs
Child c=new Child ();
}
}
Operation Result:
Conclusion:
Calling the base class construction method through super must be the first statement in the subclass construction method.
Think: Why must the constructor of the subclass be called before the construction method of the parent class is run? Can you turn around? Why can't it be reversed?
The constructor (constructor) is a special method. It is used primarily to initialize an object when it is created, to assign an initial value to an object member variable, and to always use the new operator in the statement that creates the object. A particular class can have more than one constructor, which is an overload of the constructor, depending on the number of arguments or different types of arguments. The function of a constructor is primarily used to define the state of the initialization when the class's object is created.
So the function of the constructor is simply to initialize and initialize a new object.
Java inherits post-lesson jobs