如何在其他类中引用变量?Player类初始化正确性咨询
问题:初始化依赖其他类的变量时遇到困惑
我感觉自己的实现方式有误,虽已查阅资料,但仍无法理解如何初始化需要引用其他类的变量。以下是相关代码:
Player类
public class Player { //instance variables private String name; private ScoreCard card; private int fullDriveYards; private int fullDrives; private int drivesOnTarget; }
ScoreCard类的变量定义
public class ScoreCard { private int totalStrokes; private int versusPar; private LinkedList<Integer> playerScoreCard; }
我未编写ScoreCard类的实现,但附上其变量定义以便理解。以下是我编写的Player类构造函数,用于初始化实例变量,请帮我判断是否正确:
// Constructor for objects of class Player public Player(String PlayerName) { // initialize all instance variables // look for and handle a null reference for playerName // to initialize this.card create ScoreCard instance and assign reference this.name = PlayerName; PlayerName = "UNKNOWN"; ScoreCard card = this.card; this.card = new ScoreCard(); this.longestDrive = 0; this.fullDriveYards = 0; this.fullDrives = 0; this.drivesOnTarget = 0; }
解答
你的构造函数存在几个问题,修正要点如下:
- 空值处理逻辑错误:当前先把参数直接赋值给
this.name,再修改参数为"UNKNOWN",完全起不到处理空值的作用。正确做法是先判断参数是否为null,再给this.name赋值。 - 冗余代码:
ScoreCard card = this.card;这句没有任何实际意义,直接创建ScoreCard实例并赋值给this.card即可。 - 无效变量引用:代码里的
this.longestDrive = 0;,但Player类的实例变量中并没有longestDrive,属于错误引用,需要删除。 - int类型变量的初始化是合理的,虽然Java中int默认值为0,但显式初始化也没问题。
修正后的构造函数:
public Player(String PlayerName) { // 处理PlayerName为空的情况 this.name = PlayerName != null ? PlayerName : "UNKNOWN"; // 初始化ScoreCard实例 this.card = new ScoreCard(); // 初始化int类型变量 this.fullDriveYards = 0; this.fullDrives = 0; this.drivesOnTarget = 0; }
内容的提问来源于stack exchange,提问作者Amber Lyda
相关产品推荐
相关产品推荐

