14 Constructor
14 Constructor
14 Constructor
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the
object that is why it is known as constructor.
Syntax:
<class_name>(){}
Example:
class Bike{
Bike(){System.out.println("Bike is created");}
1
What is the purpose of default constructor?
Default constructor provides the default values to the object like 0, null etc. depending on the data type.
class Student{
int id;
String name;
s1.display();
s2.display();
class Student{
int id;
String name;
id = i;
name = n;
s1.display(); s2.display(); }}
2
Constructor Overloading in Java
Constructor overloading is a technique in Java in which a class can have any number of constructors that
differ in parameter lists. The compiler differentiates these constructors by taking into account the number
of parameters in the list and their type.
class Student{
int id;
String name;
int age;
id = i;
name = n;
id = i;
name = n;
age=a;
s1.display();
s2.display();
3
Difference between constructor and method in java
There are many differences between constructors and methods. They are given below
There is no copy constructor in java. But, we can copy the values of one object to another like copy
constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
By constructor
By assigning the values of one object into another
By constructor
class Student{
int id;
String name;
id = i;
name = n;
Student(Student s){
id = s.id;
name =s.name;
}
4
void display(){System.out.println(id+" "+name);}
class Student{
int id;
String name;
id = i;
name = n;
Student(){}
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();