The assignment to variable [Something] has no effect

11.3k views Asked by At

I get this warning, what does it mean?

The assignment to variable name has no effect.

I also get the same error for all 3 fields. The full code is below:

public class Module {

    private String name;
    private int bind;
    private Category category;

    public Module(String name,int bind,Category category) {
    }{
        this.name = name; // The assignment to variable name has no effect
        this.bind = bind;
        this.category = category;
    }
3

There are 3 answers

0
almightyGOSU On BEST ANSWER

Here is your problem, extra braces:

public Module(String name,int bind,Category category) {
}{ // <<<
    this.name = name;
    this.bind = bind;
    this.category = category;
}

It should be:

public Module(String name,int bind,Category category)
{
    this.name = name;
    this.bind = bind;
    this.category = category;
}
1
Mordechai On
public Module(String name,int bind,Category category) {
}{

there's an extra pair of braces, so your code is practically not inside the constructor.

Your code will be run before the constructor as an "instance initialization block", therefore, these naming refers to the instances of your class, not to the constructer arguments.

0
Laurent B On

Just to complete the answers given.

The code you have is perfectly valid. In effect, you created a constructor that does not assign any variable :

public Module(String name,int bind,Category category) {
}

and below you created an initializer code block that is called by every constructor :

{
 this.name = name;
 this.bind = bind;
 this.category = category;
}

This block effectively assigns every local variable to itself which causes the compiler to warn you about that.