Home Java Constructor in Java

Constructor in Java

0
283

In this topic, you will learn about,

Constructor in Java.

The constructor is a method of a class having two basic characteristics.

  1. The constructor has the same name as the class name.
  2. Constructor never returns any value.

Constructors are basically used for the initialization of instance variables.

Types of constructor in java:

  1. Default constructor
  2. Parameterized constructor
  3. Copy constructor

Default constructor: Constructor without any argument is called default constructor. It is called automatically when the object of a class is created.

Syntax-

Java Program to reverse a 3 digit no. using the default constructor:

JAVA Program to calculate factorial of a no. using default constructor:

Parameterized Constructor: A constructor with an argument is called a parameterized constructor.

Syntax:

Example:

How to invoke or call

It is called when we pass argument(s) with during the creation of an object.

Syntax:

ClassName ObjectName=new ClassName(Arguments);

Example:

Constructor Overloading in Java:

In a class, there may be more than one constructor and it is known as constructor overloading. In the case of constructor overloading, all the constructors of a class will have different types and numbers of arguments.

JAVA Program to show the constructor overloading:

Copy Constructor: A constructor having an object of its own class as an argument is called a copy constructor.

A copy constructor is used to create an object using another object of the same class.

Syntax:

Example:

How to invoke or call

It is called when we pass an existing object as an argument during the creation of an object.

Syntax:

ClassName ObjectName=new ClassName(OldObjectName);

Example:

Number obj1=new Number();
Number obj2=new Number(obj1);

Program to show the use of copy constructor in Java:

Comment below if you have queries related to the above topic, Constructor in Java.

NO COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here