✓ CONSTRUCTOR .

EXPLAIN ;

> A like as, constructor in Java is similar to a method that is invoked when an object of the class is created.

> Unlike Java methods, a constructor has the same name as that of the class and does not have any return type.

> For example, class Bike { Bike() { // constructor body } } Here, Bike () is a constructor.

TYPES ;

> Now is the correct time to discuss the types of the constructor, so primarily there are two types of constructors in java,

> No-argument constructor
> Parameterized Constructor

NO-ARGUMENT CONSTRUCTOR ;

> A constructor that has no parameter is known as the default constructor.

> If we don’t define a constructor in a class.

> then the compiler creates a default constructor(with no arguments) for the class.

> And if we write a constructor with arguments or no arguments then the compiler does not create a default constructor.

PARAMETERIZED ;

> constructor that has parameters is known as parameterized constructor.

> If we want to initialize fields of the class with our own values, then use a parameterized constructor.

PROGRAM ;

classEmp

     / / constructor with one argument

{

     Emp(String name)

    {

        System.out.println("Constructor with one "+

                      "argument - String : "+ name);

    }

    // constructor with two arguments

   Emp(String name, intage)

    {

        System.out.println("Constructor with two arguments : "+

                " String and Integer : "+ name + " "+ age);

    }

     // Constructor with one argument but with different

    Emp(log id)

    {

        System.out.println("Constructor with one argument : "+

                                            "Log : + id);

    }

}

class company

{

    public static void main(String[] args)

    {

        // Creating the objects of the class named 'Emp’

        // by passing different arguments

        Emp staff = newEmp("Sp”);

        // Inside the constructor with two arguments

        // the constructor with one argument of

        Emp staff 2 = neEmp("sp”, 22);

        Emo staff 3 = newEmp(1234567);

    }

}

Leave a Comment