Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Class → constructors



Constructors in Java A constructor in Java is a special method that is used to initialize objects. It is called when an instance of a class is created. The constructor has the same name as the class and does not have a return type. Here are the types of constructors in Java: Default Constructor: A constructor is called “Default Constructor” when it doesn’t have any parameter. For example:
public class Bicycle { public Bicycle() { // This is a default constructor } }
Parameterized Constructor: A constructor that initializes the instance variables with the provided values is known as a parameterized constructor. For example:
constructor with parameter public class Bicycle { private int gear; public Bicycle(int gear) { this.gear = gear; // This is a parameterized constructor } }
In the above example, gear is a parameter. The this keyword is used to distinguish between class attributes and parameters with the same name.