Constructors in Java: Rules For Creating Java Constructor
Constructors in Java: Rules For Creating Java Constructor
Every time an object is created using the new() keyword, at least one
constructor is called.
Output:
Bike is created
Output:
0 null
0 null
In this example, we have created the constructor of Student class that have
two parameters. We can have any number of parameters in the constructor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display()
{System.out.println(id+" "+name);}
Output:
111 Rama
222 Amit
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.
Constructor overloading in Java is a technique of having more than one
constructor with different parameter lists. They are arranged in a way that
each constructor performs a different task. They are differentiated by the
compiler by the number of parameters in the list and their types.
Output:
111 Rama 0
222 Amit 25