What is the difference between two code snippets with and without a constructor?

Asked

Viewed 71 times

4

I’m having trouble understanding what a constructor does. Does it initialize a variable so it’s not null? If yes, this would not be solved easily by doing what is written in the second code snippet?

public class Node<E> {
    var previous: Node<E>? = null
    var next: Node<E>? = null
    var value: E? = null

    constructor(e: E) {
        value = e
    }
}
public class Node<E>(e: E) {
    var prev: Node<E>? = null
    var next: Node<E>? = null
    var value: E? = e
}

1 answer

5


It would be interesting to see this: What good is a builder?.

When you initialize a field in the class you’re saying that you want the compiler to write a constructor for you where it initializes every time you instantiate that class and you don’t care what order it will do it and you don’t want it to do anything else.

If this guarantee is not enough and you want more, you want to have control of how to initialize the fields, then you can write the constructor on your own.

But there’s a catch in the first code. One of the constructors does exactly what the compiler would do in this exact situation. But an empty constructor (no parameters) has also been created that does not initialize the same field, so its value will be null on startup if you call this constructor. It may have been intentional or accidental, but the first code has this capability, the second does not, the field will be initialized in all instances if the empty constructor is called, since the initializations that the compiler places will not exist in this method.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.