Sunteți pe pagina 1din 8

Constructors

ETL LABS PVT LTD – JAVA PROGRAMMING 44


Constructors
A constructor in Java is a special method that is
used to initialize objects. The constructor is
called when an object of a class is created. It can
be used to set initial values for object attributes:

Rules for creating constructor


•Constructor name must be the same as its 3
class name
• A Constructor must have no explicit return
type
• A Java constructor cannot be abstract, static,
final, and synchronized

ETL LABS PVT LTD – JAVA PROGRAMMING 45


Example of Constructor

ETL LABS PVT LTD – JAVA PROGRAMMING 46


Types of Constructors

Default constructor
(No argument Constructors) Parameterized Constructors

Type 1 Type 2
Without argument With argument

ETL LABS PVT LTD – JAVA PROGRAMMING 47


Default Constructor
A constructor is called "Default Constructor"
when it doesn't have any parameter.
Syntax of default constructor:
<class_name>()
4 {
}
Example of default constructor
In this example, we are creating the no-arg
constructor in the Bike class. It will be invoked
at the time of object creation.

ETL LABS PVT LTD – JAVA PROGRAMMING 48


Parameterized Constructor
A constructor which has a specific number
of parameters is called a parameterized
constructor.

The parameterized constructor is used to 3


provide different values to the distinct
objects. However, you can provide the same
values also.

Constructors can also take parameters,


which is used to initialize attributes.

ETL LABS PVT LTD – JAVA PROGRAMMING 49


Constructor Overloading
In Java, a constructor is just like a method but without return
type. It can also be overloaded like Java methods.

Constructor overloading in Java is a technique of having more


than one constructor with different parameter lists. They are
arranged in a way that each constructor performs a different
task. They are differentiated by the compiler by the number of
parameters in the list and their types.

ETL LABS PVT LTD – JAVA PROGRAMMING 50


Difference between constructor and method

Constructor Method

A constructor is used to initialize the state of an object. A method is used to expose the behavior of an object.

A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default constructor if you don't


The method is not provided by the compiler in any case.
have any constructor in a class.

The constructor name must be same as the class name. The method name may or may not be same as class name.

ETL LABS PVT LTD – JAVA PROGRAMMING 51

S-ar putea să vă placă și