Java Fundamentals Part 3 Constructor and Method Overloading

  • 2021-11-13 01:31:49
  • OfStack

Directory 1, Define Constructor 2, Initialize Method Priority 3, Method Overload 4, Summary

In Methods and Data Members, we mentioned that objects in Java are initialized when they are created (initialization). When initialized, the data members of the object are assigned initial values. We can explicitly initialize. If we don't assign an initial value to the data member, the data member will take the default initial value according to its type. Explicit initialization requires us to determine the initial value when writing the program, which is sometimes inconvenient. We can use the constructor (constructor) to initialize the object. Constructors can initialize data members and specify specific operations. These actions are performed automatically when the object is created

1. Define the constructor

The constructor is a method. Like ordinary method 1, we define the constructor in the class. Constructors have the following basic characteristics:

The name of the constructor is the same as the name of the class Constructor has no return value

We define the constructor for the Human class:


public class Test
{
    public static void main(String[] args)
    {
        Human aPerson = new Human(160);
        System.out.println(aPerson.getHeight());
    }

}

class Human
{
    /**
     * constructor
     */
    Human(int h)
    {
        this.height = h;
        System.out.println("I'm born");
    }

    /**
     * accessor
     */
    int getHeight()
    {
        return this.height;
    }

    int height;
}

The above program will print

I'm born
160

The constructor can receive the parameter list like ordinary method 1. Here, the constructor Human() Accepts 1 integer as a parameter. In the body of the method, we assign the integer parameter to the data member height . The constructor does two things when the object is created:

Provide the initial value this. height = h for the data member; Perform the specific initial operation System. out. println ("I 'm born");

In this way, we can flexibly set the initial value when calling the constructor, without being as constrained as displaying initialization.

How is the constructor called? When we create classes, we all use new Human() The way. In fact, we are calling the constructor of Human class. When we do not define this method, Java provides a blank constructor to call when using new. But when we define the constructor, Java calls the defined constructor when creating the object. At the time of the call, we supplied a parameter 160. As you can also see from the final run results, the object's height is indeed initialized to 160.

2. Priority of initialization method

In methods and data members, we can see that if we provide explicit initializers, the data members will take explicit initializers instead of default initializers. But if we both provide an explicit initializer and initialize the same 1 data member in the constructor, the final initializer will 由构造器决定 . For example, the following example:


public class Test
{
    public static void main(String[] args)
    {
        Human aPerson = new Human(160);
        System.out.println(aPerson.getHeight());
    }

}

class Human
{
    /**
     * constructor
     */
    Human(int h)
    {
        this.height = h; 
    }

    /**
     * accessor
     */
    int getHeight()
    {
        return this.height;
    }

    int height=170; // explicit initialization
}

The running result is:

160

The final initialization value of the object is the same as the value 1 in the build method. Therefore:

构建方法 > 显式初始值 > 默认初始值

(In fact, the so-called priority is related to the order of execution at initialization, and I will go into this point later.)

3. Method overloading

You can define more than one constructor in a class, such as:


public class Test
{
    public static void main(String[] args)
    {
        Human neZha   = new Human(150, "shit");
        System.out.println(neZha.getHeight()); 
    }

}

class Human
{
    /**
     * constructor 1
     */
    Human(int h)
    {
        this.height = h;
        System.out.println("I'm born");
    }

    /**
     * constructor 2
     */
    Human(int h, String s)
    {
        this.height = h;
        System.out.println("Ne Zha: I'm born, " + s);
    }

    /**
     * accessor
     */
    int getHeight()
    {
        return this.height;
    }

    int height;
}

Run results:

Ne Zha: I'm born, shit
150

Two constructors are defined above, both named Human. The two constructors have different parameter lists.

When you create an object using new, Java is based on the 提供的参数 To decide which 1 constructor to build. For example, when building neZha, we provided two parameters: the integer 150 and the string "shit", which corresponds to the parameter list of the second build method, so Java will call the second build method.

In Java, Java will also be based on 方法名 And 参数列表 To determine which method to invoke, which is called a method overload (method overloading). Build methods can be overloaded, as can ordinary methods, such as the following breath () method:


public class Test
{
    public static void main(String[] args)
    {
        Human aPerson = new Human();
        aPerson.breath(10);
    }

}

class Human
{
    /**
       * breath() 1
       */
    void breath()
    {
        System.out.println("hu...hu...");
    }


   /**
    * breath() 2
    */
    void breath(int rep)
    {
        int i;
        for(i = 0; i < rep; i++) {
            System.out.println("lu...lu...");
        }
    }

    int height;
}

Run results:

lu...lu...
lu...lu...
lu...lu...
lu...lu...
lu...lu...
lu...lu...
lu...lu...
lu...lu...
lu...lu...
lu...lu...

As you can see, since one parameter is supplied at the time of the call: the integer 10, the second breath () method with the parameter list matching it is called.

4. Summary

constructor Feature: Same name as class, no return value

constructor Purpose: Initialization, Initial Operation

Method overload: method name + parameter list- > Which 1 method is actually called


Related articles: