Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between a no-arg constructor and a default constructor in Java

Actually I can not understand that what is the difference between a no-arg constructor and a default constructor.

import javax.swing.*;

public class Test extends JFrame {
   public Test() {
     super();
     this.setSize(200,200);
     this.setVisible(true);
   }
   public static void main(Sting[] arg) {
       Test cFrame = new Test();
   }
}

Does this invoke the default constructor of this class while creating Test object called cFrame?

like image 481
amila isura Avatar asked Dec 26 '14 07:12

amila isura


People also ask

Is the default constructor a no arg constructor Java?

The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass.

What is a default no arg constructor in Java?

No-Arg Constructor - a constructor that does not accept any arguments. Parameterized constructor - a constructor that accepts arguments. Default Constructor - a constructor that is automatically created by the Java compiler if it is not explicitly defined.

Why do we need a no arg constructor?

newInstance() method, which requires a no-argument constructor to create an instance. It's effectively equivalent to the new Entity(). This method throws InstantiationException if it doesn't found any no-argument constructor in the Entity class, and that's why it's advised to provide a no-argument constructor.


1 Answers

The default constructor is a no-args constructor that the Java compiler inserts on your behalf; it contains a default call to super(); (not supper()) which is the default behavior. If you implement any constructor then you no longer receive a default constructor.

JLS-8.8.9. Default Constructor says (in part),

If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.

If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.

like image 53
Elliott Frisch Avatar answered Oct 30 '22 12:10

Elliott Frisch