Constructors in Java
Constructors in Java
What is Constrctor?
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 is a special type of method which is used to
initialize the object.
Every time an object is created using the
new() keyword, at least one constructor is
called.
Need of Constructor
Think of a Box class & its object
When it comes to exist?
Can a box be there with no value defined for its
dimensions?
So constructors are used to assign values to the
class variables at the time of object creation, either
explicitly done by the programmer or by Java itself
(default constructor).
Rules for creating Java
constructor
}
Default Constructor Example1
Output:-5
Default Constructor Example 2
Output:-
Java Parameterized Constructor
A constructor which has a specific number of parameters
is called a parameterized constructor.
It is used to provide different values to distinct
objects.You can provide the same values also
Java Parameterized Constructor Example
Output
Difference between Java Constructor &
Method
Java Copy Constructor
There is no copy constructor in Java.
We can copy the values from one object to another like copy
constructor in C++.
Ways to copy the values of one object into another
I. By constructor
II. By assigning the values of one object into another
III. By clone() method of Object class
Copy Constructor
A copy constructor is a special type of constructor that creates
an object using another object of the same Java class. It
returns a duplicate copy of an existing object of the class.
Copy Constrctor Example
Output