繁体   English   中英

如何覆盖方法使其仅返回数字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? 我无法理解压倒一切。

编辑:谢谢你的回答。 有人可以解释为什么你需要一个与父类和子类构造函数具有相同签名的构造函数? 还是我弄错了?

调用Roll时,在代码中进行以下更改:

Dice d = new CheatDice(5);

现在你会看到2被退回。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM