Home  >  Article  >  Java  >  In Java, what do you mean by default constructor?

In Java, what do you mean by default constructor?

PHPz
PHPzforward
2023-08-27 10:53:08893browse

In Java, what do you mean by default constructor?

Constructor function is 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);
   }
}

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 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[]);
}

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);
   }
}

output

100
1000

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete