本代码演示了如何在Java中创建类、实例化对象以及使用构造函数和方法。让我们改进代码并添加一些注释来增强可读性。
class Playground {
int score; // 球员得分
int balls; // 投球数
int catches; // 接球数
String playerName; // 球员姓名
// 构造函数,用于创建只包含得分和接球数的球员对象
public Playground(String playerName, int score, int catches) {
this.playerName = playerName;
this.score = score;
this.catches = catches;
}
// 构造函数,用于创建包含得分、接球数和投球数的球员对象
public Playground(String playerName, int score, int catches, int balls) {
this.playerName = playerName;
this.score = score;
this.catches = catches;
this.balls = balls;
}
public static void main(String[] args) {
// 创建两个Playground类的实例
Playground player1 = new Playground("Dhoni", 100, 3);
Playground player2 = new Playground("Jadeja", 56, 2, 30);
// 调用player1对象的batting()方法,并打印得分和球员姓名
player1.batting();
// 调用player2对象的allrounder()方法,并打印得分、球员姓名、投球数和接球数
player2.allrounder();
}
// batting()方法,打印球员姓名和得分
public void batting() {
System.out.println("Player Name: " + playerName + ", Score: " + score);
}
// allrounder()方法,打印球员姓名、得分、接球数和投球数
public void allrounder() {
System.out.println("Player Name: " + playerName + ", Score: " + score + ", Catches: " + catches + ", Balls: " + balls);
}
}
此版本代码更清晰地展示了类的结构,并对变量和方法进行了更具描述性的命名。 通过添加注释,代码的可读性和可理解性得到了显著提高。 输出结果与原代码一致。