What is a constructor (method)

What is a constructor

java constructor, also known as construction method, is a special function in java. The function name is the same as and has no return value.

Function: it is generally used to initialize member properties and methods, that is, after the new object is generated, the object properties and methods are called.

In real life, many things have certain attributes and behaviors as soon as they appear. For example, once a person is born, he has age, height, weight and will cry; As soon as a car is produced, it has color, appearance, operation, etc. With these, we can define these natural properties and behaviors in the constructor. When new instantiates the object, it will have these properties and methods. There is no need to redefine them, so as to speed up the programming efficiency.

Constructors run as soon as an object is established, initialize the object, including properties and execute statements in methods.
In general, the function is executed only when the object is called. Add functions to the object in the way of ". Method name".

When an object is created, the constructor runs only once.
A general function can be called multiple times by the object.

Characteristics of constructors
1. The function name is the same as the class name
2. There is no need to define the return value type. (unlike the return value of void type, void has no specific return value type; the constructor has no type)
3. You can't write a return statement. (there are no return value types, so you don't need a return statement.)

Note: general functions cannot call constructors. Only constructors can call constructors.

Example
1. There is only one method defined in the parameterless constructor. When a new object is, the corresponding constructor is called to execute this method. There is no need to write ". Method name".

package javastudy;

public class ConfunDemo {
    public static void main(String[] args) {
        Confun c1=new Confun();            //Output Hello World. As soon as the new object is established, the corresponding constructor Confun() will be called and the println statement will be executed.
    }
}
class Confun{        
    Confun(){        //Define the constructor and output Hello World
        System.out.println("Hellow World");
    }
}

Output: Hello World

2. The parameterized constructor passes the actual parameter value to the private variable when the new object is used, which is equivalent to completing the setter function.

package javastudy;

public class ConfunDemo3 {
    public static void main(String[] args){
        Person z=new Person("zhangsan",3);        //When instantiating an object, new Person() directly calls the Person constructor and turns the argument, which is equivalent to the setter function
        z.show();
    }
}

class Person{
    private String name;
    private int age;
    public Person(String n,int m){                //There is a parameter constructor to pass parameter values to private member variables
        name=n;
        age=m;        
    }
    //Getter / / when instantiating an object, you need a getter to obtain the actual parameter value after completing the sett function.
    public String getName(){
        return name;
    }
    public int getAget(){
        return age;
    }
    public void show(){                           //Get the private value and print out
        System.out.println(name+"\n"+age);
    }
}

Output:
zhangsan
3

In the above code, we can also put the output statement in the show() method directly in the constructor. When the new object, we can directly output the value, as shown below

package javastudy;

public class ConfunDemo3 {
    public static void main(String[] args){
        Person z=new Person("zhangsan",3);        //When instantiating an object, new Person() directly calls the Person constructor and turns the argument, and executes the output statement at the same time
    }
}

class Person{
    private String name;
    private int age;
    public Person(String n,int m){                //There is a parameter constructor to realize the function of passing parameter values to private member variables, and directly output values at the same time
        name=n;
        age=m;
        System.out.println(name+"\n"+age);
    }
}

Output:
zhangsan
3

or

class ConFun
{
    public static void main(String[] args){
        Person z=new Person(20,"zhangsan");
        System.out.println(z.getAge()+z.getName());
    }
}

class Person
{
    private int age;
    private String name;
    public Person(int x,String y){
        age=x;
        name=y;
    }
    public int getAge(){
        return age;
    }
    public String getName(){
        
        return name;
    }
}

3. After an object is created, the constructor runs only once.

If you want to assign a new value to the value of the object, you need to use the set and get methods. At this time, it is used as a general function

As follows:

package javastudy;

public class ConfunDemo4 {
    public static void main(String[] args) {
            PersonDemo s=new PersonDemo("Li San",33);        //When a new object is, the corresponding constructor is called and the value is passed. At the same time, the same object cannot be new multiple times, otherwise an error will be reported.
            s.setName("Li Wu");                            //After the object is created, if you want to change the value, you need to use the set/get method to reset the new value
            s.setName("Alpha dog");                        //And the object can be called multiple times.
            s.print();
    }
}
class PersonDemo{
    private String name;
    private int age;
    PersonDemo(String n,int m){                //A parameterized constructor is established to assign values to two private variables name and age, and output values at the same time
        name=n;
        age=m;
        System.out.println("full name:"+name+"Age:"+age);
    }
    public void setName(String x){            //The set method is used to assign a value to name again
        name=x;        
    }
    public String getName(){                //Get method, which is used to get the assignment of name
        return name;
    }
    public void print(){
        System.out.println(name);
    }
}

Output results:

Name: Li San age: 33
Alpha dog

4. Default constructor

When there is no constructor defined in a class, the system will add a default empty parameter constructor to the class to facilitate the initialization of the class. However, the empty constructor is hidden.

As follows, the default constructor of Person() {} is hidden.

class Person
{  
    //Person(){}
}

When the constructor is customized in this class, the default constructor is not available.

If you still want a constructor, you need to add it manually in your class.

5. Overload of constructor

Constructor is also a kind of function, which also has the function overloading feature.

class Person
{  
    private String name;
    private int age;
 
    Person()
    {
        System.out.println("A:name="+name+":::age="+age);
    }
 
    Person(String n)
    {
        name = n;
        System.out.println("B:name="+name+":::age="+age);
    }
 
    Person(String n,int a)
    {  
        name=n;
        age=a;
        System.out.println("C:name="+name+":::age="+age);
    }
 
}
 
class PersonDemo2
{
    public static void main(String[] args)
    {
        Person p1=new Person();
        Person p2=new Person("lishi");
        Person p3=new Person("lishi",10);
    }
}

Output results:
A:name=null:::age=0
B:name=lishi:::age=0
C:name=lishi:::age=10

class Person
{  
    private String name;
    private int age;
 
    Person()
    {
        System.out.println("A:name="+name+":::age="+age);
        cry();
    }
 
    Person(String n)
    {
        name = n;
        System.out.println("B:name="+name+":::age="+age);
        cry();
    }
 
    Person(String n,int a)
    {  
        name=n;
        age=a;
        System.out.println("C:name="+name+":::age="+age);
        cry();
 
    }
    void cry()
    {
        System.out.println("Cry...............");
    }
 
}
 
class PersonDemo2
{
    public static void main(String[] args)
    {
        Person p1=new Person();
        Person p2=new Person("lishi");
        Person p3=new Person("lishi",10);
    }
}

Output results:
A:name=null:::age=0
Cry...
B:name=lishi:::age=0
Cry...
C:name=lishi:::age=10
Cry...

Tags: Java

Posted on Sun, 21 Nov 2021 18:51:49 -0500 by QSDragon