在Java中,提高代码复用性的一个方法是使用setter方法。setter方法允许您为类的属性设置值,同时保持代码的可维护性和可读性。以下是如何使用setter方法提高代码复用性的示例:
public class Person {
private String name;
private int age;
private String address;
// Getter and Setter methods for name
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// Getter and Setter methods for age
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
// Getter and Setter methods for address
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.setName("John Doe");
person.setAge(30);
person.setAddress("123 Main St");
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
System.out.println("Address: " + person.getAddress());
}
}
通过使用setter方法,您可以轻松地更改类的属性值,而无需修改类的内部实现。这使得代码更具可维护性和可读性,同时提高了代码复用性。当您需要为类的属性设置不同的值时,只需调用相应的setter方法即可。