As we know Java is an object oriented language. Everything is objects in Java. We also know that objects have something (instance variables / fields) and do something (methods).
a constructor
is used to initialize variables, it is not a method. you can however choose to create constructor, if you do not the JVM will create a default constructor
.
Directly from the JLS (Chapter 8)
A constructor is used in the creation of an object that is an instance of a class (§12.5, §15.9). The SimpleTypeName in the ConstructorDeclarator must be the simple name of the class that contains the constructor declaration; otherwise a compile-time error occurs.
In all other respects, the constructor declaration looks just like a method declaration that has no result (§8.4.5).
Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding.
Constructor in Java
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. The constructor actually returns the current class instance (You cannot use return type yet it returns a value). There are basically two rules defined for the constructor.
1)Constructor name must be same as its class name 2)Constructor must have no explicit return type
Types of constructors
1)Default constructor (no-arg constructor)
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
2)Parameterized constructor
class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Can we say Contructors are Methods in Java?
If you're new to Java and trying to grasp the concept for the first time, you can think of constructors as factory methods. (Like in Python for instance where a constructor just a method called __init__
.) You should however move on quickly and understand that there are many differences. To name a few:
this
reference.new
, and has a special bytecode, invokespecial
, while instance methods are called by obj.method()
which typically compiles to the invokevirtual
bytecode.