如何重写一个方法使其 return 仅成为数字 2? (Java)
How do I override a method to make it return the number 2 only? (Java)
import java.util.Random;
public class Dice {
private int numOfSides;
private int[] sideValues = new int[getNumOfSides()];
public Dice(int numOfSides) {
this.setNumOfSides(numOfSides);
for(int i = 0; i < this.sideValues.length; i++) {
sideValues[i] = i + 1;
}
}
public int Roll() {
return (new Random()).nextInt(getNumOfSides()) + 1;
}
public int getNumOfSides() {
return numOfSides;
}
public void setNumOfSides(int numOfSides) {
this.numOfSides = numOfSides;
}
}
import java.util.Random;
public class CheatDice extends Dice {
public CheatDice(int numOfSides) {
super(numOfSides);
}
public int Roll() {
return 2;
}
}
public class DiceTester {
public static void main(String[] args) {
Dice a = new Dice(6);
System.out.println(a.Roll());
Dice b = new Dice(2120202);
System.out.println(b.Roll());
Dice d = new Dice(5);
System.out.println(d.Roll());
}
}
如何重写 Roll() 方法以便它只打印数字 2?我无法理解覆盖。
编辑:感谢您的回答。有人可以解释为什么您需要一个与父子 class 构造函数具有相同签名的构造函数吗?还是我记错了?
调用 Roll 时在代码中进行以下更改:
Dice d = new CheatDice(5);
现在您会看到正在返回 2。
import java.util.Random;
public class Dice {
private int numOfSides;
private int[] sideValues = new int[getNumOfSides()];
public Dice(int numOfSides) {
this.setNumOfSides(numOfSides);
for(int i = 0; i < this.sideValues.length; i++) {
sideValues[i] = i + 1;
}
}
public int Roll() {
return (new Random()).nextInt(getNumOfSides()) + 1;
}
public int getNumOfSides() {
return numOfSides;
}
public void setNumOfSides(int numOfSides) {
this.numOfSides = numOfSides;
}
}
import java.util.Random;
public class CheatDice extends Dice {
public CheatDice(int numOfSides) {
super(numOfSides);
}
public int Roll() {
return 2;
}
}
public class DiceTester {
public static void main(String[] args) {
Dice a = new Dice(6);
System.out.println(a.Roll());
Dice b = new Dice(2120202);
System.out.println(b.Roll());
Dice d = new Dice(5);
System.out.println(d.Roll());
}
}
如何重写 Roll() 方法以便它只打印数字 2?我无法理解覆盖。
编辑:感谢您的回答。有人可以解释为什么您需要一个与父子 class 构造函数具有相同签名的构造函数吗?还是我记错了?
调用 Roll 时在代码中进行以下更改:
Dice d = new CheatDice(5);
现在您会看到正在返回 2。