Constructor and Its Types
Constructor and Its Types
Every time an object is created using the new() keyword, at least one
constructor is called.
2. Parameterized constructor
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any
parameter.
class Bike1{
Bike1(){System.out.println("Bike is created");}
//main method
Output:
Bike is created
Q) What is the purpose of a default constructor?
The default constructor is used to provide the default values to the object
like 0, null, etc., depending on the type.
int id;
String name;
//creating objects
s1.display();
s2.display();
Output:
0 null
0 null
class Student4{
int id;
String name;
id = i;
name = n; }
void display()
System.out.println(id+" "+name);
s1.display();
s2.display();
Output:
111 Karan
222 Aryan
Constructor Overloading in Java
In Java, a constructor is just like a method but without return type. It can also
be overloaded like Java methods.
class Student5{
int id;
String name;
int age;
id = i;
name = n;
There are many ways to copy the values of one object into another in Java.
They are:
o By constructor
In this example, we are going to copy the values of one object into another
using Java constructor.
//Java program to initialize the values from one object to another object.
class Student6{
int id;
String name;
id = i;
name = n;
Student6(Student6 s){
id = s.id;
name =s.name;
s1.display();
s2.display();
Output:
111 Karan
111 Karan
Copying values without constructor
We can copy the values of one object into another by assigning the objects
values to another object. In this case, there is no need to create the
constructor.
1. class Student7{
2. int id;
3. String name;
5. id = i;
6. name = n;
7. }
8. Student7(){}
10.
14. s2.id=s1.id;
15. s2.name=s1.name;
16. s1.display();
17. s2.display();
18. }
19. }
Test it Now
Output:
111 Karan
111 Karan
Q) Does constructor return any value?
Yes, it is the current class instance (You cannot use return type yet it returns
a value).
id = i;
name = n;
age=a;
s1.display();
s2.display();
Output:
111 Karan 0
222 Aryan 25
The Java compiler The method is not provided by the compiler in any
provides a default case.
constructor if you don't
have any constructor in a
class.
The constructor name The method name may or may not be same as the
must be same as the class class name.
name.
o By constructor
In this example, we are going to copy the values of one object into another
using Java constructor.
//Java program to initialize the values from one object to another object.
class Student6{
int id;
String name;
id = i;
name = n;
Student6(Student6 s){
id = s.id;
name =s.name;
s1.display();
s2.display();
}
}
Output:
111 Karan
111 Karan
class Student7{
int id;
String name;
id = i;
name = n;
Student7(){}
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
Output:
111 Karan
111 Karan