要完善Java普通类的逻辑,你需要遵循以下步骤:
public class MyClass {
private String name;
private int age;
// 构造方法
public MyClass(String name, int age) {
this.name = name;
this.age = age;
}
// getter 和 setter 方法
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 class MyClass {
// ... 属性
// 方法:计算年龄
public int calculateAge(int years) {
return this.age + years;
}
// 方法:更改名称
public void changeName(String newName) {
this.name = newName;
}
}
public class Main {
public static void main(String[] args) {
MyClass myClass = new MyClass("John", 30);
// 调用方法
int newAge = myClass.calculateAge(5);
System.out.println("New age: " + newAge);
// 更改名称
myClass.changeName("Jane");
System.out.println("New name: " + myClass.getName());
}
}
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class MyClassTest {
@Test
public void testCalculateAge() {
MyClass myClass = new MyClass("John", 30);
assertEquals(35, myClass.calculateAge(5));
}
@Test
public void testChangeName() {
MyClass myClass = new MyClass("John", 30);
myClass.changeName("Jane");
assertEquals("Jane", myClass.getName());
}
}
遵循这些步骤,你可以完善Java普通类的逻辑并确保其功能正确。