Virtual Jasper Virtual Jasper - 2 months ago 17
Java Question

Java compile error: incompatible types: void cannot be converted to xxx

Here is my simple demo class.

public class NewClass {
private int foo=setFoo(123);

public int getFoo() {
return foo;
}

public void setFoo(int foo) {
this.foo = foo;
}
}


I try to initialize the field foo to 123, by it own setter. The compiler give me error:

error: incompatible types: void cannot be converted to int
private int foo=setFoo(123);


Netbeans suggest me to initialize it in Constructor.

Does any friends know what is exactly happening? and why?

Answer

public void setFoo(int foo) - return type void

private int foo=setFoo(123) - assigning void to int

instead create constructor and assign like this

public class NewClass {
    private int foo;

    public int getFoo() {
        return foo;
    }
    //constructor 
    public NewClass() {
        this.foo = 123; // some default value you like
    }
    //constructor 
    public NewClass(int foo) {
        this.foo = foo;
    }
}

else try using getter setter method for the private variable foo

Comments