‹‹ Previous
Next ››
Java Constructor
- Constructor is defined in the class.
- Constructor is similar to a method in the class.
- Constructor name is same as class name.
- Constructor does not have return data type.
- Constructor can receive arguments.
- Constructor is used to create and initialize the object.
- If no constructor is defined in the class, then java provides default constructor.
Example
class student {
int rollno;
String name;
student() // constructor is defined, it has same name as class name
{
rollno = 10;
name = "Rajesh";
}
display ()
{
System.out.println ("roll no is " + rollno);
System.out.println ("name is "+ name);
}
}
class demostudent {
public static void main (String args[])
{
student s1 = new student(); // this statement will call the constructor to
// initialize s1 object.
s1.diaplay();
}
}
Explanation of the program
- The program defines a class named 'student'.
- Within the class 'student', a constructor is defined, it has same name as class name.
- The constructor 'student' assigns values to variables.
- The class 'demostudent' is defined to create and access class 'student'.
- The statement 'student s1 = new student()' creates an object named s1.
- The above statement is also initialize variables of the object s1 using constructor student().
- The method display() is called using the object s1 to display values of variables.
Output of the program
roll no is 10
name is Rakesh
Parameterized Constructor
- When we passing the arguments to constructor. It is called parameterized constructor.
- Parametrized constructors are used to initialize the variables from user.
Example
class student {
int rollno;
String name;
student(int r, String n) // Parametrized constructor
{
rollno = r;
name = n;
}
display ()
{
System.out.println ("roll no is " + rollno);
System.out.println ("name is "+ name);
}
}
class demostudent {
public static void main (String args[])
{
student s1 = new student(10, "Rajesh"); // this statement will call the constructor to
// initialize s1 object.
s1.diaplay();
}
}
Explanation of the program
- In the above program, two arguments are passed to constructor 'student'.
- Arguments are assigned to variables of the object s1.
Output of the program
roll no is 10
name is Rakesh
‹‹ Previous
Next ››