Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
Java Setter 失效?深入理解对象实例化与状态维护_创想鸟

Java Setter 失效?深入理解对象实例化与状态维护

Java Setter 失效?深入理解对象实例化与状态维护

本文深入探讨了Java中setter方法看似不生效的常见问题,其根本原因在于每次操作时重复创建了新的对象实例。通过分析对象生命周期和变量作用域,我们将阐明为何频繁实例化会导致状态丢失,并提供将对象作为方法参数传递或作为类成员变量维护等解决方案。掌握正确的对象管理方式,是确保程序状态正确更新的关键。

引言:Java 对象状态更新的常见陷阱

许多java开发者在初学阶段会遇到一个令人困惑的问题:即使调用了对象的setter方法来更新属性,后续获取到的值却依然是初始值。这往往给人一种setter方法没有生效的错觉。然而,问题的核心并非setter本身,而是对java对象生命周期和实例化机制的误解。本文将通过一个实际案例,深入剖析这一现象的根源,并提供有效的解决方案。

问题剖析:为何 setter 似乎没有更新值?

让我们来看一个典型的代码场景,其中尝试通过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对象实例。有以下几种常见的解决方案:

Kive Kive

一站式AI图像生成和管理平台

Kive 171 查看详情 Kive

立即学习“Java免费学习笔记(深入)”;

1. 将对象作为方法参数传递

这是最直接也最推荐的方式之一。在应用程序的入口点(例如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); // 首次调用时传递对象    }}

优点: 这种方法清晰地表明了数据流,易于理解和调试。它避免了全局状态的潜在问题,适用于大多数场景。缺点: 在大型应用中,如果很多方法都需要访问同一个对象,参数列表可能会变得很长。

2. 将对象作为类的静态成员变量

如果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 失效?深入理解对象实例化与状态维护的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/853169.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
怎么安装linux下的安装包
上一篇 2025年11月27日 19:00:32
抖音赚钱渠道_抖音收益来源
下一篇 2025年11月27日 19:00:34

相关推荐

发表回复

登录后才能评论
关注微信