Java Programming
About Lesson

Initialisation of variables is must in programming languages. If the data elements are not initialized before they are used in executable statements it leads unexpected results. Java datatypes provides default values to be stored inside the variables when they were not initialized.
Since class is a user defined data type out of which objects can be declared, the object has the responsibility of initializing its members.

Initialisation of objects can be done in two ways:

  1. through .(dot) operator (if they are not private)
  2. through constructors

Initializing data members of class is possible only when the class definition is known. To over come this problem, OOP languages are equipped with a mechanism called constructor.

Definition of Constructor and features:

A constructor is a special member method of the class. It is special because of the following characteristics:

  • The name of constructor is same as its class name
  • It is not mandatory to define constructor for the class since it is available by default.
  • There will be no return type in the definition of constructor
  • Constructor cannot be invoked using object
  • Constructor cannot be abstract, static, final and synchronized
  • Access Modifiers can be used for constructor declaration. It controls the object creation. In other words, we can have public, protected, private or default constructors.

 

//java program to show how constructor can be used to intialise class objects
class sample
{
int a;
float b;
sample()
{
a=1;
b=2;
}
void showData()
{
System.out.println(“a=”+a+”\n”+”b=”+b);
}
}
public class ConstructorExample1 {

public static void main(String[] args) {
sample s;
s=new sample();
s.showData();
}

}

The default constructor is also called as non-parameterised constructor. But it is possible to pass arguments for the constructor. Then it is known as parameterized constructor. The parameterized constructor can be used to provide different values to each object.

 

Overloading Constructors
Overloading is a concept of Object-Oriented Programming using which a method may have more than one definition.
It is not mandatory to define default constructor. But when a constructor is overloaded, then it is mandatory to define default constructor.

//java program to show how constructor can be overloaded and used to intialise class objects
class sample
{
int a;
float b;
sample(int x, float y) //overloaded constructor with parameters
{
a=x;
b=y;
}
sample() //redefining default constructor
{
a=1;
b=2;
}
void showData()
{
System.out.println(“a=”+a+”\n”+”b=”+b);
}
}
public class ConstructorExample {

public static void main(String[] args) {
sample s;
s=new sample(10,15.5f);
s.showData();
sample t=new sample();
t.showData();

}

}

 

 

 

You cannot copy content of this page