Home > Software design >  what is an alternative to a setter method?
what is an alternative to a setter method?

Time:11-13

So first I'd like to specify that I'm still learning to program. I have a Profile Class that takes several attributes like name, age, education etc, but i don't know how to create a method that lets the user "update" their data. The variables are also public and the method needs to be able to update every variable, so I can't use a setter method in this case since it won't even take more than exactly one parameter. Can anyone please help?

public class Profile (
     public String name;
     public int age; 
     public string address;
     public string email;
     public string phone; 

public void update_profile(string a, int b, string c, string d, string f)
{ 
     this.name = a;
     this.age = b;
     this.address = c;
     this.email = d;
     this.phone = f;
}

CodePudding user response:

I think you are looking for this kind of example

public class Main {
public static void main(String[] args) {

    Profile profile1 = new Profile("Dinuka",25,"Sri lanka","[email protected]","0787777");
    
    Profile profile2 = new Profile();
    profile2.setName("add");
    profile2.setAge(45);
    profile2.setAddress("add");
    profile2.setEmail("add");
    profile2.setPhone("add");
}
}

class Profile {
private String name;
private int age;
private String address;
private String email;
private String phone;

public Profile() {

}

public Profile(String name, int age, String address, String email, String phone) {
    this.name = name;
    this.age = age;
    this.address = address;
    this.email = email;
    this.phone = phone;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getAge() {
    return age;
}

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

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPhone() {
    return phone;
}

public void setPhone(String phone) {
    this.phone = phone;
}

}

CodePudding user response:

Please use standard Java convention with getter and setter methods. Variables should be private and every variable should have separate setter and getter for setting and getting values:

public class Profile (
 private String name;
 private int age; 
 private String address;
 private String email;
 private String phone; 

 public setName(String name) {
   this.name = name;
 }

 public getName() {
   return name;
 }

 public setAge(int age) {
   this.age = age;
 }

 public getAge() {
   return age;
 }
 ...


}
  • Related