Home  >  Article  >  Java  >  Do all classes in Java have a parameterless constructor by default?

Do all classes in Java have a parameterless constructor by default?

青灯夜游
青灯夜游Original
2020-10-26 13:42:445856browse

When there is no constructor defined, each class has a default no-parameter constructor. At this time, the class has only one constructor; and when you explicitly define the constructor of the class, then There is no default constructor. All the constructors of this class are those defined.

Do all classes in Java have a parameterless constructor by default?

Related recommendations: "Java Video Tutorial"

Construction method, as the name suggests, is when you new It is called when an object is created. When there is no constructor defined, each class has a default no-argument constructor. At this time, the class has only one constructor; and when you explicitly define the constructor of the class, there is no default constructor. , all the constructors of this class are those defined; for example: define a Student class:

class Student1{
//不定义构造方法,此时默认的构造方法是Student1();new
//一个对象时只能这样构造,Student1 s=new Studnet1();
}
另外再写一个有定义构造方法的类:
class Student2{
Student(String name);
Student(String name,int age);
}

Student2 has two constructors, but there is no default constructor

When creating a Student2 object, you can only use two construction methods

Student2 s2=new Student2("xiaoming");
Student2 s2=new Student2("xiaoqiang",12);

You can also provide more construction methods with any number of parameters. When constructing the object, it is constructed according to the construction method you defined.

The above is the detailed content of Do all classes in Java have a parameterless constructor by default?. 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