Java constructor with default values

Default Constructor in Java

Constructor

A default constructor in Java is created by the compiler itself when the programmer doesn’t create any constructor. The purpose of the default constructor is to initialize the attributes of the object with their default values.

What is Default Constructor in Java?

A default constructor is created only when we don’t declare any constructor in our code. Then, by default, the compiler automatically creates a default constructor.

Since we know the role of the constructor in Java, the question is, what will happen when there is no constructor available during object creation?

But firstly, we need to look at an important case where we try to access any variable without initialization. Here in this example, we’ll be simply declaring the variables but won’t initialize them with their default values.

Читайте также:  Javascript узнать текущий url

Compilation error:

And indeed, this is what you might have expected. The above code has thrown multiple errors. Why? Because we didn’t bother to initialize the variables with their default values. Also, these variables are declared within the static method, so these are static variables. It is important to provide static variables with their default values.

Now, we’ll provide default values for them.

Now, the code is working properly. So, the above example highlighted a common mistake that we, as programmers, might do while creating objects as well.

Instance Variables

Instance variables are the ones declared as a property of a class but outside of constructors, methods, or blocks of the class.

So, initializing the instance variables is also mandatory. Here comes the role of a default constructor in Java that assigns these instance variables with their default values.

Note: We usually call the default constructor a no-arg constructor but they are not actually the same. A no-arg constructor is still a constructor created by the user and not by the compiler. Although they both have the same purpose, one is created automatically while the other is created by the user.

Default Constructor Example

Let us take an example of a product that comprises data such as id , product_name , and also price .

Notice what happens when no constructor is declared in the code by a programmer, and still, we are trying to access the instance variables.

It works! The above code didn’t throw any error because the Java compiler provided a default constructor for the code to initialize the attributes with default values. Yes, this default constructor is invisible.

Purpose of a Default Constructor

As discussed above, the purpose of the default constructor is to provide the default values to the object. An integer will be initialized with 0 0 0 , double with 0 . 0 0.0 0 . 0 , boolean with f a l s e false f a l s e , and String with n u l l null n u l l . It depends on the type of instance variable declared in the class from which an object is created.

Let’s consider another case where we’ll create a parameterized constructor.

Compilation error:

We have created a parameterized constructor in our code, and we are trying to access the default constructor. It throws an error .

Note: When we create any constructor manually, then the compiler will not insert the default constructor. So, we’ll also have to create the default constructor manually, if needed.

If we have created a parameterized constructor on our own and by any chance, we tried to call the default constructor, then it is our responsibility to also create our own default constructor as well.

But yes, this only occurs when we call the default constructor, whereas we have created parameterized constructor only. You can see the same in the code given below.

The problem didn’t occur here because we neither created nor called the default constructor. We had a parameterized constructor and we are just calling it, so there isn’t any need for default constructor.

Conclusion

  • A default constructor in Java is created automatically by the online Java compiler when the programmer doesn’t create any constructor in the entire program.
  • It is created to assign the default values to the instance variables of the class when an object is created.
  • Default constructors are sometimes called no-arg constructors since they both work the same. But no-arg constructor is created by the user while default constructor can only be created by the compiler.

Источник

Constructor in java

Default Constructor in java

How does the constructor work in heap memory?

When the constructor gets the call, it does check the initial value of variables. Even the developer can provide the initial value to variables. In the above example developer is not providing any initial value to variables. So, the default constructor provides the default values to a variable and initializes them in heap memory.

java class constructor

Important points about Constructor

1. The name of the constructor must be exactly the same as the class name. If you are providing any other name, then the compiler will show an error.

2. A class can have any number of constructors as methods. Hence, It means we can overload the constructors.

3. A constructor doesn’t have a return type. The constructor looks like a method, but it is different than methods and doesn’t return anything. Java Constructor is by default of type void.

4. You can use a return statement inside the constructor. But you can’t return any value. Because Constructors are by default of type void. Using a return statement, you can return the control flow from the constructor.

5. Every Class contains a default constructor by default. This constructor is provided by the compiler.

6. If the programmer doesn’t declare any parameterized constructor then the compiler automatically inserts a default constructor at the back end.

7. If the Programmer provides any parameterized constructor then the compiler doesn’t provide the default constructor. It is the responsibility of the programmer to provide the default constructor. Otherwise, the compiler throws the exception.

8. By use of this keyword and super keyword, you can call one constructor to another constructor. This property is known as constructor chaining.

9. In java, the constructor is by default with a default access modifier. In the same way, you can use any access modifier with a Java constructor. Hence, you can make public, protected, or private constructors.

Rules for the constructor in java

1. The constructor name must be the same as its class name.
2. A constructor doesn’t have an explicit return type.
3. Java constructors cannot be abstract, static, final, and synchronized
4. We can use an access modifier while declaring a constructor. So, we have private,
protected, public, or, default constructors. Access modifier is used to control its access i.e.
which other classes can call the constructor.

Two types of constructors in Java

1. Default constructor(without arguments/parameters)
2. Parameterized constructor.

1. Default constructor(without arguments/parameters)

It is a constructor that has no parameter known as the default constructor. If you are not creating any constructor in a class, then the compiler creates a default constructor for the class. But if you are creating any constructor (with arguments or default) then the compiler does not create a default constructor. Then it is the responsibility of a programmer to create a constructor according to the use in an application.

public class Student < int rollNo; String className; //default construcotr Student() < System.out.println("This is default constructor of class Student"); >public static void main (String arg[]) < // Creating a object that will call the default constructor Student newStudent = new Student(); >>

Output: This is the default constructor of class Student

The reason behind the use of a default constructor?

The default constructor is used to provide the default values to the variables, objects like 0, null, etc., depending on the type. So, Here I will show you the compiler provides automatically a default constructor that provides default values.

Example of default constructor with default values

public class Student < int rollNo; String className; boolean isFromCity; public void studentData() < System.out.println("This is default constructor of class provides default values"); System.out.println("Roll no = "+ rollNo); System.out.println("Class Name = "+ className); System.out.println("Is student belongs to city wp-block-quote">

Output:
This is default constructor of the java class provides default values
Roll no = 0
Class Name = null
Is student belongs to city = false
Memory representation with default values:

Heap memory in java

2. Parameterized constructor

A constructor that has a parameter is known as a parameterized constructor. By use of parameterized constructor, you can also initialize the values of fields. You can provide the values to the parameterized constructors when you are creating an object.

Let’s see Java program to print student details using the constructor:

class_Name(paramerters/agruments) < // body of constructor >
public class Student < String name; int rollNo; String className; boolean isFromCity; Student(String name, int rollNo, String className, boolean isFromCity) < this.name = name; this. rollNo = rollNo; this.className = className; this.isFromCity = isFromCity; >public void studentData() < System.out.println("Name of Student = " + name); System.out.println("Roll no = "+ rollNo); System.out.println("Class Name = "+ className); System.out.println("Is student belongs to city = "+ isFromCity); >public static void main (String arg[]) < // Creating object and providing some values by using parameterized constructor Student student1 = new Student("Ravi", 1, "MCA", false); student1.studentData(); Student student2 = new Student("Ram", 2, "MCA", true); student2.studentData(); >>

Output:
Name of Student = Ravi
Roll no = 1
Class Name = MCA
Is student belongs to city = false
Name of Student = Ram
Roll no = 2
Class Name = MCA
Is student belongs to city = true

Important point: In this example, we created only a parameterized constructor. If we create an object by using the default constructor, then it will throw a compilation error.

Student student3 = new Student(); // compilation error

The compiler always provides a default constructor to the class but if the programmer providing any parameterized constructor then it’s the programmer’s responsibility to provide the default constructor.

1. Quiz, Read the below code and do answer.

The name of a constructor and the name of a class must be ___.

Click on anyone to know the answer.

It can be same or different

2. Quiz, Read the below code and do answer.

We can create a constructor inside but the placement of the constructor should be ___.

Click on anyone to know the answer.

At the beginning of class

3. Quiz, Read the below code and do answer.

We use a constructor in java because we want to ___.

Click on anyone to know the answer.

Initialization of variables with passed data
Accepting other objects as inputs

4. Quiz, Read the below code and do answer.

JVM allocates memory to an object after execution of ______?

Источник

Оцените статью