
许多java开发者在初学阶段会遇到一个令人困惑的问题:即使调用了对象的setter方法来更新属性,后续获取到的值却依然是初始值。这往往给人一种setter方法没有生效的错觉。然而,问题的核心并非setter本身,而是对java对象生命周期和实例化机制的误解。本文将通过一个实际案例,深入剖析这一现象的根源,并提供有效的解决方案。
让我们来看一个典型的代码场景,其中尝试通过setter方法修改一个角色的防御值,但后续查询却发现值未改变:
// MainChar.java - 角色属性定义
public class MainChar {
private int health = 100;
private int defence = 25; // 默认防御值
private int strength = 15;
private int mana = 10;
public int getHealth(){ return health; }
public int getStrength() { return strength; }
public int getDefence() { return defence; }
public int getMana() { return mana; }
public void setDefence(int newDefence) {
this.defence = newDefence;
}
public void setHealth(int newHealth) { this.health = newHealth; }
public void setMana(int newMana) { this.mana = newMana; }
public void setStrength(int newStrength) { this.strength = newStrength; }
}
// 包含业务逻辑的类 (简化版)
public class GameSystem {
public static void startmenu(){
// ... 菜单显示和用户输入逻辑 ...
// 假设用户输入 path
int path = 0; // 模拟用户输入
// ... 获取用户输入 ...
SouthValley(path);
}
public static void SouthValley(int selectedPath){
MainChar stats = new MainChar(); // 关键问题所在!每次调用都会创建一个新对象
do {
switch(selectedPath){
// ... 其他 case ...
case 5:
System.out.println("--------------------------------");
System.out.println("Defence: " + stats.getDefence()); // 此时可能输出 25
// 重新调用菜单,但没有传递当前 stats 对象
startmenu();
break;
case 6:
stats.setDefence(50); // 尝试将当前 stats 对象的防御值设为 50
System.out.println("Updated Defence: " + stats.getDefence()); // 此时会输出 50
// 重新调用菜单,但没有传递当前 stats 对象
startmenu();
break;
default:
startmenu();
break;
}
}
while(selectedPath < 7); // 实际循环条件可能更复杂
}
public static void main(String[] args) {
startmenu(); // 程序的入口点
}
}在这个例子中,当用户选择选项6时,stats.setDefence(50)被调用,并且紧接着System.out.println(stats.getDefence())会正确地输出50。然而,当程序回到主菜单,用户再次选择选项5(查看统计数据)时,stats.getDefence()却又输出了默认值25。
根本原因在于: SouthValley方法内部的MainChar stats = new MainChar();这行代码。每次调用SouthValley方法时,都会创建一个全新的MainChar对象。每个MainChar对象都有自己独立的defence属性副本,其初始值都是25。当你在case 6中调用stats.setDefence(50)时,你确实修改了当前这个stats对象的defence属性。但是,当SouthValley方法执行完毕(例如,通过startmenu()递归调用回到主菜单并再次进入SouthValley),或者下次SouthValley被调用时,MainChar stats = new MainChar();会再次被执行,从而创建一个全新的MainChar对象,其defence属性又回到了默认值25。之前那个被修改为50的对象,由于没有被引用,最终会被垃圾回收。
要解决这个问题,关键在于确保在需要保持状态更新时,始终操作同一个MainChar对象实例。有以下几种常见的解决方案:
立即学习“Java免费学习笔记(深入)”;
这是最直接也最推荐的方式之一。在应用程序的入口点(例如main方法)创建一次MainChar对象,然后将其作为参数传递给所有需要操作它的方法。
// GameSystem.java (修改后 - 参数传递方式)
import java.util.Scanner;
public class GameSystem {
public static void startmenu(MainChar characterStats){ // startmenu 接受 MainChar 对象
int path;
Scanner startscan = new Scanner(System.in);
System.out.println("-----------------------");
System.out.println("Enter Shop : 1");
System.out.println("Enter house : 2");
System.out.println("Enter town square : 3");
System.out.println("Leave town : 4");
System.out.println("Check stats : 5");
System.out.println("Chosen path: ");
System.out.println("update defence : ");
path = startscan.nextInt();
SouthValley(path, characterStats); // 调用 SouthValley 时传递 characterStats
}
public static void SouthValley(int selectedPath, MainChar characterStats){ // SouthValley 接受 MainChar 对象
// 不再在这里创建 MainChar 对象
do {
switch(selectedPath){
case 1:
System.out.println("You Entered shop");
System.out.println("-----------------------------");
break;
case 2:
System.out.println("You Entered you house");
break;
case 3:
System.out.println("You Entered Town Square");
break;
case 4:
System.out.println("You left the town");
// FirstPath(); // 如果 FirstPath 也需要 characterStats,也应传递
break;
case 5:
System.out.println("--------------------------------");
System.out.println("Defence: " + characterStats.getDefence()); // 获取传递进来的对象的防御值
startmenu(characterStats); // 再次进入菜单,需要传递 characterStats
break;
case 6:
characterStats.setDefence(50); // 修改传递进来的对象的防御值
System.out.println("Updated Defence: " + characterStats.getDefence());
startmenu(characterStats); // 再次进入菜单,需要传递 characterStats
break;
default:
startmenu(characterStats); // 默认情况也需传递
break;
}
}
while(selectedPath < 7);
}
public static void main(String[] args) {
MainChar playerStats = new MainChar(); // 只创建一次 MainChar 对象
startmenu(playerStats); // 首次调用时传递对象
}
}优点: 这种方法清晰地表明了数据流,易于理解和调试。它避免了全局状态的潜在问题,适用于大多数场景。 缺点: 在大型应用中,如果很多方法都需要访问同一个对象,参数列表可能会变得很长。
如果MainChar对象代表的是整个应用程序共享的唯一状态(例如,一个单例模式),并且操作它的方法都是静态方法,那么可以将其声明为类的静态成员变量。这样,MainChar对象只会被初始化一次,并且在整个程序的生命周期中都可用。
// GameSystem.java (修改后 - 静态成员变量方式)
import java.util.Scanner;
public class GameSystem {
private static MainChar playerStats = new MainChar(); // 将 MainChar 声明为静态成员变量,只初始化一次
public static void startmenu(){
int path;
Scanner startscan = new Scanner(System.in);
System.out.println("-----------------------");
System.out.println("Enter Shop : 1");
System.out.println("Enter house : 2");
System.out.println("Enter town square : 3");
System.out.println("Leave town : 4");
System.out.println("Check stats : 5");
System.out.println("Chosen path: ");
System.out.println("update defence : ");
path = startscan.nextInt();
SouthValley(path); // SouthValley 不再需要参数
}
public static void SouthValley(int selectedPath){
// 不再在这里创建 MainChar 对象,直接使用静态成员变量 playerStats
do {
switch(selectedPath){
case 1:
System.out.println("You Entered shop");
System.out.println("-----------------------------");
break;
case 2:
System.out.println("You Entered you house");
break;
case 3:
System.out.println("You Entered Town Square");
break;
case 4:
System.out.println("You left the town");
// FirstPath();
break;
case 5:以上就是Java Setter 失效?深入理解对象实例化与状态维护的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号