Constructor
It is a function that has same name as the class name. It can't have any return type , not even void. It is implicitly called whenever an object of a class is called. It is used to initialize the data members of the class
It is a function that has same name as the class name. It can't have any return type , not even void. It is implicitly called whenever an object of a class is called. It is used to initialize the data members of the class
There are two types of constructors in java.
- Default constructor:- it doesn't take any arguments.it initializes all the data members. If no Constructor is defined in the class then java compiler gives you a default constructor which assigns default values to the data members according their data type.(this constructor is taken back from the java compiler if the user defines even one constructor of its own)
- parameterized constructor:- it takes arguments and assigns these values to the data members. Example of Constructor
Class Student
{
int age, String name;
public Student() //default constructor
{
Age= 10;
Name= "abc"}
public Student (int a) //parameterized Constructor
{
Age=a;
Name="xyz";}
public Student (int a, String str) //parameterized Constructor
{
Age=a;
Name=str;
}
}Constructor overloading:
Example:
String str="Computer";
str.substrint(2); //output---> mputer (Extracts all the letters from index 2 to the last index.
str.substrint(2, 4); //output-->mp(Extracts letters from index 2 to 3)
Related Posts
Continue learning with these related articles

Logic Gates for ISC Class 11: Truth Tables, Universal Gates, Half and Full Adder
ISC Class 11 Computer Science notes on logic gates: AND, OR, NOT, NAND, NOR, XOR and XNOR with truth tables, why NAND and NOR are universal gates, and half adder and full adder circuits with their Boolean expressions.
Decimal to Binary Conversion in Java: 3 Programs with Examples
How to convert a decimal number to binary on paper and in Java: three programs (String, place value and Integer.toBinaryString), binary to decimal, a dry run and common mistakes.
Sum of First n Natural Numbers in Java (Loop and Formula)
Find the sum of the first n natural numbers in Java with a for loop, a while loop and the formula n(n + 1)/2, with a dry run and the sums of even numbers, odd numbers, squares and cubes.