Void in a constructor

Viewed 83

Java 14.

class InitByConstructionVoid{
    String aux;

    public void InitByConstructionVoid(){
        this.aux = "aux";
    }

}


class InitByConstruction{
    String aux;

    InitByConstruction(){
        this.aux = "aux";
    }

}


public class Ex2 {
    private String str;

    public static void main(String [] args){

        InitByConstruction con = new InitByConstruction();
        System.out.println("InitByConstruction: " + con.aux);

        InitByConstructionVoid conVoid = new InitByConstructionVoid();
        System.out.println("InitByConstructionVoid: " + conVoid.aux);

    }
}

Result:

InitByConstruction: aux
InitByConstructionVoid: null

Could you help me understand what is the meaning of that word void here? I mean why it influenced like that.

4 Answers

The keyword "void" in any programming language usually means that the function will not have a return type, so please erase the void syntax if you are looking to get a value for aux in the scope of your InitByConstructionVoid() function.

void is a type. By adding it to the signature of InitByConstructionVoid, you've degraded the constructor to a normal instance method.

It is not a constructor, it is a method with the same name. and when you use this:

InitByConstructionVoid conVoid = new InitByConstructionVoid();

in fact, you are calling the default constructor which is not implemented by you. so the body is empty and the field "aux" is not set in that.

to make it more clear, try to write that with an input and you will see that your code does not compile.

InitByConstruction(){
        this.aux = "aux";
    }

This should be public for it to be acessible outside the class.Hence the null problem.

Related