The constructor method is a special method within a class that executes when the object of the class is created, and is used to initialize a portion of the content. For example a diary, the default is to record the time should be the day, then you can write such a class
Class note{
Date date;
Public Note () {
This.date = new Date (); New date indicates the day
}
}
This means that every time you create a diary, the date of the diary is automatically set to the day.
Constructors can have parameters such as
Class note{
Public Note (date date) {}
The constructor in this class has parameters so the object is created with a new Note (date) date is a date, the object is created in parentheses when the argument is written, then this object will be created with the corresponding constructor to initialize.
Each class will have at least one constructor, you do not write the class will also have a default constructor, you write your own constructor, then there is no default constructor in the class, which is very important, such as:
Class note{
There is no write constructor in this class, he will have a default constructor. Create the object with new Note () Yes.
Class note{
Public Note (date date) {}
} This class writes itself a constructor, so the default constructor does not exist, the object is created with the new note (date), and the new note () is wrong because there is no function like public Note () in the class.
Inheritance of constructors:
Subclasses call the constructor of the parent class before calling the constructor.
Like what
Class parent{
Public Parent () {
System.out.println ("Parent class invocation");
}
}
Class Child extends parent{
Public Child () {
System.out.println ("sub-class invocation");
}
}
When you create a child object, you will first output the "Parent class call" and then output the "Subclass call"
In addition, the constructor of the parent class that can be displayed in the subclass constructor, such as public child () {super ();}
You can also select a constructor for the parent class, such as public child () {super (date)}
This is equivalent to calling the public parent (date date) of the parents class as the constructor.
Note here: If you want to display the constructor of the calling parent class in the subclass, then super must be in the first row of the subclass constructor.
Java Construction methods