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); } }
Run result:
农作物的名称:玉米 农作物的数量:100
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft