Class 10 ICSE - Java

Constructors

Definition



Constructors is a special type of function or member method of a class used to intialize default values to instance variables.It is same as that of class name
Let us understand,this defination by an example:


The following characteristics of constructors are:
  1. The name of the constructor is same as that of class name,that is from above example we can see that class Abc has same name constructor Abc().
  2. In a class there can be more than one constructors.
  3. The main purpose of constructor is to intialize the objects of the class
  4. Every java program has a constructor i.e default constructors
  5. There is no return type in a constructor, not even void also

Invoke a Constructor



When we create a main() function of xyz classname,then we create object of the class that is:
So during creation of object of a class each time,at least one constructor(that is default constructor) is invoked to assign initial value to data members of a class.
Here in the above object creation,we first created class object as obj using new() keyword.After that default constructor of a same class name Abc() is invoked.


Example:

Write a program a and print employee name and id of xyz company.

Types of constructors



There are basically 2 types of constructors:

  1. default Constructors
  2. Parametrized Constructors


Default Constructors



Default constructors are also called as non-parameterized or no-arguments constructor.These constructors does not contain any parameters.Whenever we define any default constructors,we dont pass any parameters inside the member method.



As shown in above example,to invoke a default constructors we can simply invoke while creating class object.

test ob=new test(); // default

If any constructor is not defined for the class,then the java compiler will automatically includes a default constructor.That is a constructor with no argument passed.

Parameterized Constructors



Parameterized constructors,are those constructors in which we pass parameters inside member functions.It allow programmers to intialize instance variable with our own values.



From the above example,to invoke a Parameterized constructor,we will provide values while creating object.If not then compiler will show error.

test ob=new test(7,3);//Parameterized
Example for both Default and Parameterized Constructors:

Write a program to print student name and their roll number using default and Parameterized constructor concept.



Contact Us

REACH US

SERVICES

  • CODING
  • ON-LINE PREPARATION
  • JAVA & PYTHON

ADDRESS

B-54, Krishna Bhawan, Parag Narain Road, Near Butler Palace Colony Lucknow
Contact:+ 919839520987
Email:info@alexsir.com