What is the constructor and Types of constructors in Java? What is the use of constructor in Java? What is the parametrize constructor in Java?
Constructor is used to initialize value to objects. What I mean to Initialize a value to objects. Let’s understand all the questions in detail about the contractor in Java.
What is Constructor in Java?
A constructor is a member function of a class that is called for initializing when an object is created of that class.
The constructor has the same name as that of the class’s name and its function is to initialize the object to an initial value for the class.
Important points about the constructor in java
- Constructor has no return type, not even void.
- A constructor constructs an object and provides its initial state.
- A constructor, like other class members, obeys usual access rules of a class.
class Student{ private int rollno ; private float marks; //Constructor of student class public Student() { rollno=0; marks=0; } }
see the above class has a member function with the same name as its class has and which provides initial values to its data members.
Whenever an object of the Student type will be created, the compiler will call the constructor Student() for the newly created object.
Constructor has one purpose in life, to create an instance of a class.
Student s1=new Student();
As mentioned, a constructor is a member function of a class with the same name as that of its class name.
In the above-given class definition, the constructor has been defined as a public member function. You even can define a constructor under private sections.
A constructor obeys the access rules of a class. That means a private constructor is not available to the non- member functions.
In other words, with a private constructor, you cannot create an object of the same class in a non-member function, however, the creation of objects is allowed in the member functions.
Types of Constructors in Java
The constructor in java can be of two types.
Parameterized: Those which can receive parameters.
Non-parameterized: Those who can not receive any parameters.
The above-mentioned Student class’s constructor does not take any argument However, a constructor can also take an argument. For example:
the above-defined constructor takes two values: one int and one float o construct values for the newly created object. With such a constructor, the object will be created.
with a constructor requiring arguments, objects can be created in a manner as shown above.
In short, constructor is needed to construct objects. The fields of the object are initialized in the constructors either using the passed value(in case of parameterized constructors) or using the default (in case of non- parameterized constructors).