Java Vamei Quick Tutorial 03 constructors and method overloads

Source: Internet
Author: User

Vamei Source: Http://www.cnblogs.com/vamei Welcome reprint, Please also keep this statement. Thank you!

In the method and data members, we mention that the objects in Java are initialized (initialization) when they are created. When initialized, the data member of the object is assigned the initial value. We can initialize it explicitly. If we do not give the data member the initial value, the data member takes the default initial value based on its type.

Explicit initialization requires that we determine the initial value when writing a program, which is sometimes inconvenient. We can use the constructor (constructor) to initialize the object. Constructors can initialize data members, and can also specify specific actions. These actions are performed automatically when the object is created.

Defining constructors

A constructor is a method. Like the normal method, we define the constructor in the class. Constructors have the following basic characteristics:

    1. The name of the constructor is the same as the name of the class
    2. The constructor has no return value

We define the constructors for the human class:

public class test{public    static void Main (string[] args)    {        Human Aperson = new Human;        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 program above will print

I ' m born
160

The constructor can receive a list of arguments just like normal methods. Here, the constructor human () receives an 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 for the data member This.height = h;
    • Perform a specific initial operation System.out.println ("I ' m Born");

In this way, we can set the initial value flexibly when invoking the constructor, instead of being as constrained as the display initialization.

How is the constructor called? When we created the class, we used the new Human () method. In fact, we are calling the constructor of the human class. When we do not define this method, Java provides a blank constructor to be called when new is used. But when we define the constructor, Java invokes the defined constructor when the object is created. At the time of invocation, we provide a parameter of 160. As you can see from the final run result, the height of the object is actually initialized to 160.

Priority of the initialization method

In the method and data members, we can see that if we provide an explicit initial value, the data member takes an explicit initial value instead of the default initial value. But if we both provide an explicit initial value and initialize the same data member in the constructor, the final initial value will be determined by the constructor. For example, the following:

public class test{public    static void Main (string[] args)    {        Human Aperson = new Human;        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 result of the operation is:

160

The final initialization value of the object is consistent with the value in the build method. So:

Build Method > Explicit Initial value > default initial value

(In fact, the so-called precedence is related to the order of execution at initialization, and I'll go into this later)

Method overloading

More than one constructor can be defined in a class, such as:

public class test{public    static void Main (string[] args)    {        Human Nezha   = new Human ("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;}

Operation Result:

Ne Zha:i ' m born, shit
150

The two constructors are defined above and the names are human. Two constructors have different parameter lists.

When you create an object using New, Java determines which constructor to build based on the parameters provided. For example, when building Nezha, we provided two parameters: integer 150 and string "shit", which corresponds to the parameter list of the second build method, so Java calls the second build method.

In Java, Java determines the method to invoke based on both the method name and the parameter list, which is called method overloading. The build method can be overloaded, and the common method can be overloaded, such as the following breath () method:

public class test{public    static void Main (string[] args)    {        Human Aperson = new Human ();        Aperson.breath (ten);    }} 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;}

Operation Result:

Lu...lu ...
Lu...lu ...
Lu...lu ...
Lu...lu ...
Lu...lu ...
Lu...lu ...
Lu...lu ...
Lu...lu ...
Lu...lu ...
Lu...lu ...

As you can see, the second breath () method that corresponds to the argument list is called because a parameter is provided at the time of invocation: integer 10.

Summarize

Constructor feature: same name as class, no return value

Constructor Purpose: Initialize, initial operation

Method Overloading: Method name + parameter list--which method is actually called

Java Vamei Quick Tutorial 03 constructors and method overloads

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.