2012-07-22 72 views
1

我有一个语法错误,我不知道如何解决它。该代码似乎正确的我,但是Eclipse是告诉我,“构造函数调用必须在 构造函数的第一个语句”的方法setName()setAge()构造函数和关键字'this'

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








    } 


} 

回答

5

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

public void setAge(int a){ 

    this.age = a; 
} 

public void setName(String s){ 

    this.name = s; 
} 

另外请注意,您的制定者通常不返回值,所以我已经改变了他们返回void类型。

0

作为一个说明,你的制定者应该像

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

而不是构造一个新的对象。如果你不这样做,你正在打破一个无庸置疑的Java约定。

假设你想创建一个二传手一个新的实例,你会做这样的事情

public KeywordThis setAge(a){ 
    return new KeywordThis(a); 
} 

,而不是使用this(a)。正如您尝试使用this应该只在一个构造函数中完成(为同一个类调用另一个构造函数)。

1

一旦创建了一个对象,就不能手动调用该构造函数。构造函数只能在另一个构造函数中调用。

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

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

感谢,这是非常有益的 – 2012-07-22 23:49:38

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 份额|编辑

+0

什么变化没有你使?为什么是答案? – 2013-02-28 04:10:18