簡體   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