构造函数和关键字'this'

Cac*_*AMF 1 java

我有语法错误,我不知道如何解决它.代码看起来对我来说是正确的,但Eclipse告诉我"构造函数调用必须是构造函数中的第一个语句",方法setName()setAge()

 public class KeywordThis {


    private String name;
    private int age;

    public KeywordThis(){

        this.name = "NULL";
        this.age = 0;

    }

    public KeywordThis(String s, int a){

        this.name = s;
        this.age = a;

    }

    public KeywordThis(String s){

        this.name = s;      
    }

    public KeywordThis(int a){

        this.age = a;

    }

    public int setAge(int a){

        this(a);
    }

    public String setName(String s){

        this(s);
    }






    public static void main(String args[] ){








    }


}
Run Code Online (Sandbox Code Playgroud)

Ole*_*ksi 5

你不能从实例方法中调用这样的构造函数.您希望您的setter更改您已有对象的值,而不是创建一个新对象.我想你的意思是这样做:

public void setAge(int a){

    this.age = a;
}

public void setName(String s){

    this.name = s;
}
Run Code Online (Sandbox Code Playgroud)

另请注意,您的setter通常不返回值,因此我将它们更改为返回类型void.