Constructor in java

Constructor is an interesting concept in java. A constructor is used to initialize the object.

In other words, a constructor is invoked when we create any object.A constructor initializes the data for the object.

Rules for constructor:

  1. Constructor name must be same as the class name
  2. Constructor must not have any explicit return type

There are 2 types of constructors in java.

  1. Default constructor
  2. Parameterized constructor

Default Constructor: A constructor that does not have any arguments is called default constructor.

Note: If no constructor is provided, compiler adds a default constructor to the class.

Constructor in java

When we create the object of SubNumber class in the below example, default constructor will be called.

Output : This is a default constructor

Parameterized Constructor: A constructor which has parameters is known as Parameterized constructor. We can have any number of parameters in the constructor and we can initialize objects with the same no. of parameters as per parameterized constructor.

Output : The sum is 9

What is constructor overloading?

That means we can have more than one constructor but with different number of parameters.

Output: Output of 1st constructor 9 Output of 2nd constructor 12

What is the role of a default constructor?

Default constructor assigns the default values to object or data members like 0 to int, null to String etc.

Output: 0—-null

Does constructor return any value?

Yes, it returns class instance. We cant use return type.

What else constructor can do?

It can be used like a method i.e. we can create object, call methods etc inside it.

Ask Question
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’.Select the desired category and post your question.
Print Friendly, PDF & Email
Output value in UFT
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *