我有以下抽象类:
abstract class OutDoorGames
{
protected String name;
protected int num_players;
protected int min_of_play;
abstract void game (String a,int g,int r);
};
我希望public void game
函数将值分配给对象的数据成员。
这是实施 abstract void game (String a,int g,int r)
:
class Cricket extends OuterDoorGames
{
public void game (String name,int num_players,int min_of_play)
{
OutDoorGames::name = name ;
OutDoorGames::num_players = num_players ;
OutDoorGames::min_of_play = min_of_play ;
}
}
但它在编译时给出错误..
我也试过这个:
class Cricket extends OuterDoorGames
{
public void game (String name,int num_players,int min_of_play)
{
this.name = name ;
this.num_players = num_players ;
this.min_of_play = min_of_play ;
}
}
这也行不通...... 我是Java新手......我该如何实现这个功能..... ??
答案 0 :(得分:1)
class Cricket扩展了OuterDoorGames
如果您收到OuterDoorGames cannot be resolved to a type
,那么这就是拼写错误。您的抽象类被命名为" OutDoorGames"。一旦你纠正了,你的板球课应该可以正常工作。
答案 1 :(得分:1)
首先,你的名字是错的。注意你给父抽象类OutDoorGames
的名字与你在扩展OuterDoorGames
时所写的名称不同。
作为一种练习,您还可以尝试在父抽象类中创建一个构造函数,该抽象类设置3个成员,然后从子类的构造函数中调用它
此类用法的一个示例:
public abstract class Bicycle {
// the Bicycle class has three fields
public int cadence;
public int gear;
public int speed;
// the Bicycle class has one constructor
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
// the Bicycle class has four methods
public void setCadence(int newValue) {
cadence = newValue;
}
public void setGear(int newValue) {
gear = newValue;
}
public void applyBrake(int decrement) {
speed -= decrement;
}
public void speedUp(int increment) {
speed += increment;
} }
public class MountainBike extends Bicycle {
// the MountainBike subclass adds one field
public int seatHeight;
// the MountainBike subclass has one constructor
public MountainBike(int startHeight,
int startCadence,
int startSpeed,
int startGear) {
super(startCadence, startSpeed, startGear);
seatHeight = startHeight;
}
// the MountainBike subclass adds one method
public void setHeight(int newValue) {
seatHeight = newValue;
}
}
注意激活父类构造函数的super
调用。只需将其更改为接受父类中的3个参数
答案 2 :(得分:0)
我能看到的唯一错误是第二个错误是类名错误。您定义的第一个类(您的抽象类)称为“OutDoorGames”,但您正在尝试扩展“OuterDoorGames”。