Home > Java > javaTutorial > body text

What is the use of java constructor method?

藏色散人
Release: 2019-06-01 15:10:10
Original
9069 people have browsed it

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);//这就是作用
}
Copy after login

The constructor is used when new an object,

For example

Hello hello = new Hello();
Copy after login

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

Hello hello = new Hello("hi");
Copy after login

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!

Related labels:
source:php.cn
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