代码之家  ›  专栏  ›  技术社区  ›  Brenden Baio

在Java中,将对象作为参数传递给方法的最佳方式是什么?[关闭]

  •  -1
  • Brenden Baio  · 技术社区  · 2 月前

    我想传递一个名为 user 创建于 Player 类进入我的 playerSetup 方法。然而,当我经过时 用户 进入方法,并尝试调用 user.setName() ,Java给出错误并建议我这样做 ((Player) user).setName(input.nextLine()) 相反。这很有效,但似乎有点混乱,特别是如果我也要用其他方法来做这件事的话。

    是否有更好的方法来解决这个问题,还是我被这个解决方案所困?

    主类

    public class Main {
        public static void main(String arg[]) {
            Scanner input = new Scanner(System.in);
            Player user = new Player();
            playerSetup(input, user);
            
            System.out.println(user.getName());
        }
    
        private static void playerSetup(Scanner input, Object user) {
            System.out.println("Hello, please enter your name: ");  
    /*
            user.setName(input.nextLine()); -- I would like for it to look like this,
            however it won't work and my IDE reccomends I do it like the line below.
    */
            ((Player) user).setName(input.nextLine()); // This seems messy having to reference the Player class every time
            System.out.println("Hello " + ((Player) user).getName());
        }
    }
    

    Player.java

    public class Player {
    private String name;
        public void setName(String name) {
            this.name = name;
        }
        public String getName() {
            return this.name;
        }
    }
    
    1 回复  |  直到 2 月前
        1
  •  1
  •   Talk is cheap    2 月前

    为了避免需要铸造 user Player 在你的 playerSetup 方法,您可以更改方法签名以显式接受 玩家 对象而不是泛型 Object 。这样,您可以直接拨打 玩家 没有铸造的方法。

    以下是如何修改您的 Main 类别:

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            Player user = new Player();
            playerSetup(input, user);
            
            System.out.println(user.getName());
        }
    
        private static void playerSetup(Scanner input, Player user) {
            System.out.println("Hello, please enter your name: ");
            user.setName(input.nextLine());
            System.out.println("Hello " + user.getName());
        }
    }
    

    通过更改参数类型 播放器设置 对象 玩家 ,您现在可以拨打 setName getName 直接在 用户 无需强制转换对象。这使您的代码更清晰、更易读。

    这是完整的 玩家 类以供参考:

    public class Player {
        private String name;
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getName() {
            return this.name;
        }
    }