简体   繁体   中英

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());


  }

}

How do I override the Roll() method so that it prints the number 2 only? I am having trouble understanding overriding.

EDIT: Thanks for your answers. Could someone explain why you need a constructor with the same signature as the parent and child class constructors? Or am I mistaken?

Make the following change in your code when you call Roll :

Dice d = new CheatDice(5);

Now you would see 2 is being returned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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