Home >Java >javaTutorial >What is the function of java constructor definition?

What is the function of java constructor definition?

WBOY
WBOYforward
2023-05-01 12:52:061709browse

1. Definition

The constructor can provide many special methods. As a method, the constructor is responsible for the initialization of member variables (fields) in the class.

2. Function

Assume that every time we write a class, we must execute an initialize() method. This method is to remind you that before using an object, you should first Call the initialize() method for initialization, which means that every user can execute this method. Constructors are introduced in Java to ensure that each object is initialized. Before Java has the ability to operate an object, the system will automatically call the corresponding constructor to ensure initialization.

3. Naming rules

The class name and the constructor name must be the same, so the coding style of "lowercase first letter of each method" is not the same Applies to constructors.

4. Example

package javastudy;
 
public class ConfunDemo {
    public static void main(String[] args) {
        //输出Hello World。new对象一建立,就会调用对应的构造函数Confun(),并执行其中的println语句。
        Confun c1=new Confun();            
        
    }
}
class Confun{        
    Confun(){        
        //定义构造函数,输出Hello World
        System.out.println("Hellow World");
    }
}

The above is the detailed content of What is the function of java constructor definition?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete