Home  >  Article  >  Java  >  In Java, what is the difference between default constructor and constructor with parameters?

In Java, what is the difference between default constructor and constructor with parameters?

WBOY
WBOYforward
2023-09-22 12:37:02797browse

In Java, what is the difference between default constructor and constructor with parameters?

Default Constructor

  • The default constructor is a 0-argument constructor that contains a reference to the superclass constructor The parameterless call.
  • Assigning default values ​​to newly created objects is the main responsibility of the default constructor.
  • Only when the program does not write any constructor, the compiler will write a default constructor in the code.
  • The access modifier of a default constructor is always the same as the class modifier, but this rule only applies to "public" and "default"

When does the compiler add a default constructor

  • The compiler adds a default constructor in the code only when the programmer adds a default constructor in the code without writing a constructor.
  • If the programmer writes any constructor in the code, the compiler will not add any constructor.
  • Every default constructor is a 0-argument constructor, but every 0-argument constructor is not a default constructor.

Parameterized constructor

  • A parameterized constructor is a constructor that has a specific number of parameters to be passed.
  • The purpose of parameterized constructors is to assign specific values ​​that the user wants to instance variables of different objects.
  • Parameterized constructors are written explicitly by the programmer.
  • The access modifier of a default constructor is always the same as the class modifier, but this rule only applies to the "public" and "default" modifiers.

Example

Real-time demonstration

public class Student {
   int roll_no;
   String stu_name;
   Student(int i, String n) { // Parameterized constructor
      roll_no = i;
      stu_name = n;
   }
   void display() {
      System.out.println(roll_no+" "+stu_name);
   }
   public static void main(String args[]) {
      Student s1 = new Student(1,"Adithya");
      Student s2 = new Student(2,"Jai");
      s1.display();
      s2.display();
   }
}

In the above program, the programmer defines a parameterized constructor with 2 parameters. Now the compiler doesn't add a default constructor to the code, and the programmer doesn't write any 0-argument constructors.

Output

1 Adithya
2 Jai

The above is the detailed content of In Java, what is the difference between default constructor and constructor with parameters?. 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
Previous article:Abstract classes in JavaNext article:Abstract classes in Java