When you write a constructor for a class it still has the default constructor that Java automatically provides true or false?

Overview

All Java classes have at least one constructor even if we don't explicitly define one.

In this article, we'll cover the behavior of the default constructor which sometimes causes confusion among new Java developers.

What is the default constructor?

Java doesn't require a constructor when we create a class.   However, it's important to know what happens under the hood when no constructors are explicitly defined.   

The compiler automatically provides a public no-argument constructor for any class without constructors.   This is called the default constructor. 

If we do explicitly declare a constructor of any form, then this automatic insertion by the compiler won't occur. 

What does the default constructor do?

The body of the default constructor contains a statement that calls the no-argument constructor of the superclass.

In this situation, the compiler will complain if the superclass lacks a no-argument constructor or has one that is not visible to the subclass. This means that the superclass constructor must be either public or protected.

Example

Let's say we are building an application for an auto dealership and want to represent the different vehicles.  

We can use inheritance to share code because the different categories of vehicles have some traits in common.

We'll define a superclass named Vehicle and extend the class using Car and Truck.

The compiler will not insert a default constructor into Vehicle because we defined a couple constructors. 

Our subclass named Car looks like this:

The compiler will insert a default constructor into Car:

The problem is that Vehicle does not have one so this will result in the following compile-time error:

Implicit super constructor Vehicle() is undefined for default constructor. Must define an explicit constructor.

To resolve the issue, we must add a no-argument constructor to Vehicle:

Java constructors or constructors in Java is a terminology been used to construct something in our programs. A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes. 

In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling the constructor, memory for the object is allocated in the memory. It is a special type of method which is used to initialize the object. Every time an object is created using the new() keyword, at least one constructor is called.

Note: It is not necessary to write a constructor for a class. It is because java compiler creates a default constructor if your class doesn’t have any.

How Constructors are Different From Methods in Java? 

  • Constructors must have the same name as the class within which it is defined while it is not necessary for the method in Java.
  • Constructors do not return any type while method(s) have the return type or void if does not return any value.
  • Constructors are called only once at the time of Object creation while method(s) can be called any number of times.

Now let us come up with the syntax for the constructor being invoked at the time of object or instance creation.

class Geek { ....... // A Constructor new Geek() { } ....... } // We can create an object of the above class // using the below statement. This statement // calls above constructor. Geek obj = new Geek();

The first line of a constructor is a call to super() or this(), (a call to a constructor of a super-class or an overloaded constructor), if you don’t type in the call to super in your constructor the compiler will provide you with a non-argument call to super at the first line of your code, the super constructor must be called to create an object:

Java

import java.io.*;

class Geeks {

    Geeks() { super(); }

    public static void main(String[] args)

    {

        Geeks geek = new Geeks();

    }

}

If you think your class is not a subclass it actually is, every class in java is the subclass of a class object even if you don’t say extends object in your class definition.

Need of Constructor

Think of a Box. If we talk about a box class then it will have some class variables (say length, breadth, and height). But when it comes to creating its object(i.e Box will now exist in the computer’s memory), then can a box be there with no value defined for its dimensions. The answer is no. 
So constructors are used to assign values to the class variables at the time of object creation, either explicitly done by the programmer or by Java itself (default constructor).

When is a Constructor called? 

Each time an object is created using a new() keyword, at least one constructor (it could be the default constructor) is invoked to assign initial values to the data members of the same class. 

The rules for writing constructors are as follows:

  • Constructor(s) of a class must have the same name as the class name in which it resides.
  • A constructor in Java can not be abstract, final, static, or Synchronized.
  • Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor.

So by far, we have learned constructors are used to initialize the object’s state. Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation.

Types of Constructors in Java

Now is the correct time to discuss the types of the constructor, so primarily there are two types of constructors in java: 

  • No-argument constructor
  • Parameterized Constructor

1. No-argument constructor: A constructor that has no parameter is known as the default constructor. If we don’t define a constructor in a class, then the compiler creates a default constructor(with no arguments) for the class. And if we write a constructor with arguments or no arguments then the compiler does not create a default constructor. 

Note: Default constructor provides the default values to the object like 0, null, etc. depending on the type.

Example:

Java

import java.io.*;

class Geek {

    int num;

    String name;

    Geek() { System.out.println("Constructor called"); }

}

class GFG {

    public static void main(String[] args)

    {

        Geek geek1 = new Geek();

        System.out.println(geek1.name);

        System.out.println(geek1.num);

    }

}

Output

Constructor called null 0

2. Parameterized Constructor: A constructor that has parameters is known as parameterized constructor. If we want to initialize fields of the class with our own values, then use a parameterized constructor.

Example:

Java

import java.io.*;

class Geek {

    String name;

    int id;

    Geek(String name, int id)

    {

        this.name = name;

        this.id = id;

    }

}

class GFG {

    public static void main(String[] args)

    {

        Geek geek1 = new Geek("adam", 1);

        System.out.println("GeekName :" + geek1.name

                           + " and GeekId :" + geek1.id);

    }

}

Output

GeekName :adam and GeekId :1

Remember: Does constructor return any value?

There are no “return value” statements in the constructor, but the constructor returns the current class instance. We can write ‘return’ inside a constructor.

Now the most important topic that comes into play is the strong incorporation of OOPS with constructors known as constructor overloading. JustLike methods, we can overload constructors for creating objects in different ways. Compiler differentiates constructors on the basis of numbers of parameters, types of the parameters, and order of the parameters. 

Example:

Java

import java.io.*;

class Geek

{

    Geek(String name)

    {

        System.out.println("Constructor with one " +

                      "argument - String : " + name);

    }

    Geek(String name, int age)

    {

        System.out.println("Constructor with two arguments : " +

                " String and Integer : " + name + " "+ age);

    }

    Geek(long id)

    {

        System.out.println("Constructor with one argument : " +

                                            "Long : " + id);

    }

}

class GFG

{

    public static void main(String[] args)

    {

        Geek geek2 = new Geek("Shikhar");

        Geek geek3 = new Geek("Dharmesh", 26);

        Geek geek4 = new Geek(325614567);

    }

}

Output

Constructor with one argument - String : Shikhar Constructor with two arguments : String and Integer : Dharmesh 26 Constructor with one argument : Long : 325614567

In order to know deep down into constructors there are two concepts been widely used as listed below: 

  • Constructor Chaining
  • Copy constructor

This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.


When you write a constructor for a class it still has default constructor that Java automatically provides?

it should use the constructor that requires one Point object argument and one Dimension object argument. When you are writing your own class, you don't have to provide constructors for it. The default constructor, the constructor that takes no arguments, is automatically provided by the runtime system for all classes.

Does every class in Java automatically have a default constructor?

The compiler automatically provides a no-argument, default constructor for any class without constructors.

Is Java default constructor always called?

A constructor is always called when constructing a new object, and a constructor of every superclass of the class is also called. If no constructor is explicitly called, the default constructor is called (which may or may not be declared).

Is default constructor called automatically?

Is a default constructor automatically provided? If no constructors are explicitly declared in the class, a default constructor is provided automatically by the compiler.