contructors

Java Constructors

Java Constructors

A constructor is a special type of method used to initialize an object. Constructors have the same name as the class and do not have a return type. They are automatically called when an object is created.

Default Constructor

class Dog {
    String name;

    // Default constructor
    Dog() {
        name = "Buddy";  // Initialize default value
    }

    void display() {
        System.out.println("Dog's name is " + name);
    }
}

public class ConstructorExample {
    public static void main(String[] args) {
        Dog dog1 = new Dog();  // Constructor is called here
        dog1.display();
    }
}
    

In this example, the constructor Dog() initializes the name variable with a default value of "Buddy".

Parameterized Constructor

class Dog {
    String name;

    // Parameterized constructor
    Dog(String dogName) {
        name = dogName;
    }

    void display() {
        System.out.println("Dog's name is " + name);
    }
}

public class ConstructorExample {
    public static void main(String[] args) {
        Dog dog1 = new Dog("Max");  // Passing argument to constructor
        dog1.display();
    }
}
    

The parameterized constructor allows you to provide values when creating an object. In this example, the Dog object is created with the name "Max".