[Javase Study Notes]-7.1 constructor overview and default constructor
In this section, we will learn a special function, that is, constructor.
So what is a constructor?
Since it is a function, it should be defined in the class with a function name. It is necessary to specify the result and parameter type returned by the function.
Let's take a look at it first.Features of constructor:
1. The function name is the same as the class name;
2. do not define the return value type
3. No specific return value.
From these features, this is indeed a very special function.
Let's look at an example of defining a constructor:
Class Person {private String name; private int age; // defines the constructor Person () of the Person class. // The constructor is null. {System. out. println ("person run");} public void speak () {System. out. println (name + ":" + age) ;}// test class ConsDemo {public static void main (String [] args) {Person p = new Person ();}}
Result:
The result shows that when we create an object, we execute the defined constructor.
Then we can define the constructor as follows:
Constructor: Construct a function called when an object is created. This is not easy to understand.
Then we can clearly understand the main functions of the constructor:
The role of the constructor: You can initialize the object.
We must be clear that every object created must be initialized through the constructor.
So why can we still create objects when there is no constructor in a class? This is because there is a default constructor.
What is the default constructor?
If no constructor is defined in a class, a default null parameter constructor is provided in the class.
Class Person () {}// constructor with null parameters. This is actually the default constructor in the class.
However, we must note that:If the specified constructor is defined in the class, the default constructor in the class will be absent.
For example, we define a class:
Class Demo {} // a class without any code
Are there any content in this class?
The answer is of course yes. Although this class is empty, we can create its object, that is, there is a default constructor in this class:
class Demo{Demo(){}}Obviously, this class does contain the default constructor.