If you don’t implement any constructor in your class, the Java compiler inserts default constructor into your code on your behalf. You will not see the default constructor in your source code(the .java file) as it is inserted during compilation and present in the bytecode(.class file).
Are no-arg constructor and default constructor same?
This is a confusing question for some as you may find different answers to this question from different sources. Some of you will not agree with me but as per my understanding they are different. The default constructor is inserted by compiler and has no code in it, on the other hand we can implement no-arg constructor in our class which looks like default constructor but we can provide any initialization code in it.
Default Constructor Example
class NoteBook{ /*This is default constructor. A constructor does * not have a return type and it's name * should exactly match with class name */ NoteBook(){ System.out.println("Default constructor"); } public void mymethod() { System.out.println("Void method of the class"); } public static void main(String args[]){ /* new keyword creates the object of the class * and invokes constructor to initialize object */ NoteBook obj = new NoteBook(); obj.mymethod(); } }
Output:
Default constructor Void method of the class
Although I have covered the parameterized constructor in a separate post, lets talk about it here a little bit. Lets say you try to create an object like this in above program: NoteBook obj = new NoteBook(12);
then you will get a compilation error because NoteBook(12)
would invoke parameterized constructor with single int argument, since we didn’t have a constructor with int argument in above example. The program would throw a compilation error. Learn more about parameterized constructor here.
prathima says
quick query .
Suppose a class does not have any constructor then JVM creates a constructor for the class . how does the created constructor looks like ?
Given a class looks as given below
class A{
int num;
public static void main(String args[]){
A a=new A();
}
}
Rajwinder says
it will assign zero to variable num
Lazarus says
is a no arg constructor and default constructor same? can we use the terminology interchangeably?
Chaitanya Singh says
Hey Lazarus, I have updated the guide and provided the answer to your Question.