Home  >  Article  >  Java  >  What is the use of java constructor method?

What is the use of java constructor method?

藏色散人
藏色散人Original
2019-06-01 15:10:108876browse

What is the use of java constructor method?

#The function of the Java constructor method is to initialize the class. If you do not agree on the form of any constructor, the program will get a constructor without any parameters for you. Then you can only use the method without parameters when generating an object of the class, such as: class a { }//No constructor.

The constructor method is the method with the same name as the class. Its function is to be used for initialization. The example is as follows

class Person //人类{
public Person(String n,int a) //构造方法

{
 name = n; age = a;
}
 private string name;
 private int age;
}
static void main(String[] args){
Person p = new Person("张三",14);//这就是作用
}

The constructor is used when new an object,

For example

Hello hello = new Hello();

At this time, the parameterless constructor of Hello is called;

Hello hello = new Hello("hi");

This is the parameterized constructor of Hello,

In JAVA, if you do not write a constructor, a parameterless constructor will be added by default. However, if there is already a parameterized constructor, the parameterless constructor will not be added by default. Above.

If the Hello class already has a constructor with parameters, then an error will occur when using Hello hello = new Hello(); to create an object. This is why the book emphasizes After writing a constructor with parameters, it is best to add a constructor without parameters.

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

Statement:
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