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

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

青灯夜游
Release: 2020-10-26 15:32:38
Original
5904 people have browsed it

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);
}
Copy after login

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);
Copy after login

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!

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