Home> Java> javaTutorial> body text

In Java, what do you mean by default constructor?

PHPz
Release: 2023-08-27 10:53:08
forward
827 people have browsed it

In Java, what do you mean by default constructor?

Constructor functionis similar to a method and is called when creating an object of a class. It is generally used to initialize instance variables of the class. The constructor has the same name as its class and has no return type.

The default constructor in Java initializes the data members of the class to their default values, such as 0 for int, 0.0 for double, etc. If the user does not implement an explicit constructor for the class, the constructor is implemented by the Java compiler by default.

If you observe the following example, we do not provide any constructor for it.

public class Sample { int num; public static void main(String args[]){ System.out.println(new Sample().num); } }
Copy after login

If you compile and run the above program, the default constructor will initialize the integer variable num with 0, and the result will be 0. The

javap< /strong> command displays information about a class's fields, constructors, and methods. If you (after compilation) run the above class using javap command, you can observe the default constructor added by the compiler as shown below -

D:\>javap Sample Compiled from "Sample.java" public class Sample { int num; public Sample(); public static void main(java.lang.String[]); }
Copy after login

Example

Live Demonstration

public class Sample{ int num; Sample(){ num = 100; } Sample(int num){ this.num = num; } public static void main(String args[]){ System.out.println(new Sample().num); System.out.println(new Sample(1000).num); } }
Copy after login

output

100 1000
Copy after login

The above is the detailed content of In Java, what do you mean by default constructor?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
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
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!