构造函数和关键字'this'

时间:2012-07-22 23:33:50

标签: 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[] ){








    }


}

4 个答案:

答案 0 :(得分:5)

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

public void setAge(int a){

    this.age = a;
}

public void setName(String s){

    this.name = s;
}

另请注意,您的setter通常不会返回值,所以我将它们更改为返回类型void。

答案 1 :(得分:1)

创建对象后,无法手动调用构造函数。构造函数只能在另一个构造函数中调用。

正如其他人指出的应该是:

public void setAge(int a) {
    this.a = a;
}

答案 2 :(得分:0)

作为备注,您的二传手应该看起来像

public void setAge(a) {
   this.a = a;
}

而不是构造一个新对象。如果你不这样做,那你就破坏了一个无处不在的Java约定。

假设您想在setter中创建一个新实例,您可以执行类似

的操作
public KeywordThis setAge(a){
   return new KeywordThis(a);
}

并且不使用this(a)。在尝试时使用this只能在构造函数中完成(为同一个类调用另一个构造函数)。

答案 3 :(得分:0)

公共类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);
    int b=a;
    return b;
}

public String setName(String s){

    this(s);
    String s1=s;
    return s; 
}






public static void main(String args[] ){

   KeywordThis ob1=new Keyword();
   ob1.setAge(20);
   ob1.setName("sandy");

}


}

的java 份额|编辑