Home > Java > javaTutorial > body text

What is the constructor method in java

(*-*)浩
Release: 2019-05-21 20:00:07
Original
6776 people have browsed it

The function of the constructor method is to initialize the class. If you do not agree on the form of any constructor, the program will take a constructor without any parameters for you. Then you can only use the method without parameters when generating a class object, such as: class a {}// There isn't any constructor.

What is the constructor method in java

The name of the constructor must be the same as the class name, including upper and lower case;

The constructor has no return value and cannot be modified with void. If you are not careful Adding a return value type in front of the constructor will turn the constructor into an ordinary method, and an error that the constructor cannot be found will be generated at runtime.

A class can define multiple constructors. If no constructor is defined when defining a class, the compilation system will automatically insert a parameterless default constructor, which does not execute any code.

Constructor methods can be overloaded according to the number, type, and order of parameters.

Examples are 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

Constructor is used when new an object,

For example:

Hello hello = new Hello();//这时调用的是Hello的无参数构造方法;
Hello hello = new Hello("hi");//这个是调用Hello有参数构造方法,
Copy after login

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. .

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 writing If you have a parameterized constructor, it is best to add a parameterless constructor.

The above is the detailed content of What is the constructor method in java. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!