Java Constructors
A constructor in Java is a special method that is used to
initialize objects. The constructor is called when an object of a
class is created. It can be used to set initial values for object
attributes:
Types of Constructor
In Java, constructors can be divided into three types:
1. No-Arg Constructor
2. Parameterized Constructor
3. Default Constructor
Important Notes on Java Constructors
Constructors are invoked implicitly when you instantiate objects.
The two rules for creating a constructor are:
1. The name of the constructor should be the same as the class.
2. A Java constructor must not have a return type.
If a class doesn't have a constructor, the Java compiler automatically
creates a default constructor during run-time. The default constructor
initializes instance variables with default values. For example,
the int variable will be initialized to 0
Constructor types:
No-Arg Constructor - a constructor that does not accept any arguments
Parameterized constructor - a constructor that accepts arguments
Default Constructor - a constructor that is automatically created by the
Java compiler if it is not explicitly defined.
A constructor cannot be abstract or static or final.
A constructor can be overloaded but can not be overridden.
Program 1
class Student
{
private String name;
Student() // constructor
{
name = "Rahul";
}
public static void main(String[] args)
{
Student s1 = new Student();
[Link]("The Student name is " + [Link]);
}
}
Program 2
class Student
{
int rollno;
private String name;
float marks;
Student() // Default constructor
{
rollno=100;
name = "Rahul";
marks=23;
}
public static void main(String[] args)
{
Student s1 = new Student();
[Link]("The Student rollno is " + [Link]);
[Link]("\nThe Student name is " + [Link]);
[Link]("\nThe Student marks is " + [Link]);
}
}
Program 3
public class Car
{
int modelYear;
String modelName;
public Car(int year, String name) // Parameterized constructor
{
modelYear = year;
modelName = name;
}
public static void main(String[] args) {
Car myCar = new Car(1969, "Mustang");
[Link]("Car Year and Model is");
[Link]([Link] + " " + [Link]);
}
}
Program 4 Java Program for Copy Constructor
// Java Program for Copy Constructor
import [Link].*;
class Employee
{
String name;
int id;
Employee(String name, int id) // Parameterized Constructor
{
[Link] = name;
[Link] = id;
}
Employee(Employee e) // Copy Constructor
{
[Link] = [Link];
[Link] = [Link];
}
}
class EmployeeDemo
{
public static void main(String[] args)
{
Employee e1 = new Employee("Shivam", 68);
[Link]("\nEmployeeName :" + [Link]
+ " and EmployeeId :" + [Link]);
[Link]();
Employee e2 = new Employee(e1);
[Link]("\n\nCopy Constructor used \n\n Second
Object");
[Link]("EmployeeName :" + [Link]
+ " and EmployeeId :" + [Link]);
}
}