刚刚让这个帐户提出一个问题,即我无法在线获得答案。希望在这里提出它会有所帮助。
总而言之,我需要创建一个包含两个类的源文件,一个篮球类和一个测试类。篮球类声明了3个类变量:name,number和team,并将定义两个方法:dribble()和shoot()。
这就是我的困惑,篮球类必须有一个构造函数,用于制作对象,测试者类必须使用构造函数来创建篮球运动员对象,使用点运算符来初始化实例变量并使用点运算符来调用方法。
我知道如何创建它以便构造函数使用参数来提供实例变量值。但我不确定如何才能使用它来构建对象并使用点运算符来初始化变量。
class Basketball {
String name, team;
int number;
Basketball(String playerName, int playerNumber, String playerTeam) {
name = playerName;
number = playerNumber;
team = playerTeam;
}
public void dribble() {
System.out.println(name + ", number " + number + " from the " + team +
" team is dribbling the ball down the court!");
}
public void shoot() {
System.out.println(name + ", number " + number + " from the " + team +
" team shoots the ball and.... scores!");
}
}
class BasketballTester {
public static void main(String [] args) {
Basketball player1 = new Basketball("Michael", 23, "Chicago Bulls");
Basketball player2 = new Basketball("LeBron", 6, "Miami Heats");
Basketball player3 = new Basketball("Kobe", 24, "Los Angeles Lakers");
Basketball player4 = new Basketball("Kevin", 35, "Oklahoma City Thunder");
player1.dribble();
player1.shoot();
player2.dribble();
player2.shoot();
player3.dribble();
player3.shoot();
player4.dribble();
player4.shoot();
}
}
这确实有效,但我没有使用点运算符来初始化实例变量。有人可以帮帮我吗?在此先感谢:)
答案 0 :(得分:1)
你的意思是这样吗?
Basketball player1 = new Basketball("", 1, "");
player1.name = "Joe Smith";
player1.team = "Generic Team";
player1.number = 1;
player1.shoot();
// etc...
不过,最好不要直接访问另一个类的成员变量。