CONSTRUCTORS IN JAVA
INTRODUCTION
Constructor is a special method/function that is used to initialize objects for its class and every time an object created by using the new() keyword, at least one constructor is called.
In Java programming language, a constructor is look like a block of codes similar to the other simple methods/functions.
In Java, a constructor is a block of codes similar to the other methods and it is called when an instance (object) of the class is created.
At the time of calling constructor, memory for the object is allocated in the memory.
There are two types of constructors in Java.
1. Default
2. Parameterized
DEFAULT CONSTRUCTOR IN JAVA
The default constructor does not have any parameter/argument.
In Java programming language, a default constructor can be either user defined or provided by JVM (Java Virtual Machine).
If a class does not have any constructor then during runtime Java Virtual Machine generates a default constructor that is known as system defined default constructor.
The main purpose to create a constructor in Java, is to initialize states of an object.
The below image shows, how does JVM adds constructor to a class during runtime.
If a class does not have any constructor then during runtime Java Virtual Machine generates a default constructor that is known as system defined default constructor.
The main purpose to create a constructor in Java, is to initialize states of an object.
The below image shows, how does JVM adds constructor to a class during runtime.
class D_constructor
{
D_constructor()
{
// Initializing data members
int a=7;
int b=5;
System.out.println("Sum of A & B: "+(a+b));
}
public static void main(String args[])
{
// Calling default constructor
D_constructor ob=new D_constructor();
}
}
- - - PROGRAM OUTPUT - - -
PARAMETERIZED CONSTRUCTOR IN JAVA
The parameterized constructors have certain/specific number of paramemters and these constructors are used to provide different values for distinct objects although we can pass same values too.
PARAMETERIZED CONSTRUCTOR EXAMPLE IN JAVA
class P_constructor
{
// Define the class variables ...
int r;
String n;
//Define the parameterzied constructor.
P_constructor(int roll, String name)
{
// Initiazing data members. r=roll;
r=roll;
n=name;
}
void display()
{
System.out.print("Roll number is: "+r);
System.out.print("\nStudent name: "+n);
}
public static void main(String args[])
{
// Calling the parameterized constructor.
P_constructor ob=new P_constructor(101,"Rakesh");
// Calling the display function ...
ob.display();
}
}
- - - PROGRAM OUTPUT - - -
0 Comments