Cactus BAMF
Cactus BAMF

Reputation: 333

Constructors and Keyword 'this'

I have a syntax error and I don't Know how to fix it. The code appears correct to me, but Eclipse is telling me that "Constructor call must be the first statement in a constructor" at the methods setName() and 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[] ){








    }


}

Upvotes: 1

Views: 86

Answers (4)

Santhosh
Santhosh

Reputation: 1

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);
    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 share|edit

Upvotes: 0

M. Ahmad Zafar
M. Ahmad Zafar

Reputation: 4939

Once an object has been created you can not manually call the constructor. Constructors can only be called inside another constructor.

As others have pointed out it should be:

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

Upvotes: 1

Oleksi
Oleksi

Reputation: 13097

You cannot call a constructor like that from an instance method. You want your setter to change the value of the object you already have, not create a new one. I think you mean to do this:

public void setAge(int a){

    this.age = a;
}

public void setName(String s){

    this.name = s;
}

Also note that your setters don't usually return values, so I've changed them to return type void.

Upvotes: 5

hvgotcodes
hvgotcodes

Reputation: 120178

As a note, your setters should look like

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

and not construct a new object. If you don't do this, you are breaking an ubiqutous Java convention.

Assuming you want to create a new instance in a setter, you would do something like

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

and not use this(a). Using this as you are attempting should only be done in a constructor (to invoke another constructor for the same class).

Upvotes: 0

Related Questions