Java Constructor

A constructor in Java is a special method used to initialize objects. It is called when an object of a class is created and is used to assign initial values to the instance variables of the class. The name of the constructor is the same as the class name, and it does not have a return type (not even void).

Types of Constructors in Java:

Default Constructor

  • A constructor with no parameters.
  • It initializes instance variables with default values.
Example
class Example {
// Default constructor
public Example() {
System.out.println("Default Constructor Called!");
}
}
public class Main {
public static void main(String[] args) {
// Create an object of the Example class
Example obj = new Example(); // Default constructor is called
}
}

Try it yourself

Parameterized Constructor

  • A constructor that accepts arguments.
  • It allows you to assign specific values to instance variables at the time of object creation.
Example
class Example {
// Parameterized constructor
public Example(String name) {
System.out.println("Name : "+name);
}
}
public class Main {
public static void main(String[] args) {
// Create an object of the Example class
Example obj = new Example("Joe"); // Parameterized constructor is called
}
}

Try it yourself


Constructor Overloading:

You can define multiple constructors in a class with different parameter lists.

Example
class Example {
// Default constructor
public Example() {
System.out.println("Default Constructor Called!");
}

// Parameterized constructor
public Example(String name) {
System.out.println("Parameterized Constructor Called! Name : "+name);
}

// Another parameterized constructor
public Example(String name, int age) {
System.out.println("Another parameterized Called! Name : "+name+", age: "+ age);
}
}
public class Main {
public static void main(String[] args) {
Example obj1 = new Example();
Example obj2 = new Example("John");
Example obj3 = new Example("Alice", 30);
}
}

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.