Home > Java > Javagetting Started > body text

Introduction to how to use the constructor

王林
Release: 2020-07-02 17:03:41
forward
2815 people have browsed it

Introduction to how to use the constructor

The role of constructor

(Recommended learning: java entry program)

The biggest use of the constructor is to perform initialization when creating an object.

When an object is created, the system performs default initialization for the object's instance variables. This default initialization sets all basic type instance variables to default values. This default initialization can be changed through the constructor, and the initial value is explicitly specified for the object's instance variables when the system creates the object.

Constructor usage

The following class provides a custom constructor, through which programmers can perform customized initialization operations.

(Video tutorial recommendation: java video tutorial)

Code sample:

public class ConstructorTest {
    public String name;
    public int count;

    /**
     * 提供自定义的构造器,该构造器包含两个参数,提供了自定义构造器,则不会再提高无参构造器了。
     * @param name
     * @param count
     */
    public ConstructorTest(String name, int count) {
        // 构造器里的 this 代表它进行初始化的对象
        // 下两行代码将转入的 2 个参数赋给 this 所代表对象的 name 和 count 实例变量
        this.name = name;
        this.count = count;
    }

    /**
     * main 方法
     * @param args
     */
    public static void main(String[] args) {
        // 使用自定义的构造器来创建对象,系统会对该对象进行自定义的初始化
        ConstructorTest corn = new ConstructorTest("玉米", 100);

        //输出两个实例变量
        System.out.println("农作物的名称:" + corn.name);
        System.out.println("农作物的数量:" + corn.count);
    }
}
Copy after login

Run result:

农作物的名称:玉米
农作物的数量:100
Copy after login

The above is the detailed content of Introduction to how to use the constructor. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template