Generate Random Number Method in Interface Class

1.1k Views Asked by At

I have an interface class and in this class I need to create an abstract method that generates a random int. However, when I try to compile I get an error because abstract classes cannot have bodies. How can I create an abstract method that generates a random int? I also need to specify an upper limit (I said 40).

{
    /**
     * This method generates a random number. 
     *
     * @param  y a sample parameter for a method
     * @return   the result produced by sampleMethod
     */
     Random rnd = new Random();
     System.out.println(rnd.nextInt(40));

}
2

There are 2 best solutions below

0
On

You said it yourself, abstract methods can't have bodies.

I suggest you write an absract class that has a concrete method that produces your random int and then have classes that extend from your abstract class.

Remember that an interface can only have abstract methods and static final variables.

0
On

In JAVA abstract class can have method with a body, abstract method dose not have a body of course

   abstract class Test{

        public void method(){
            System.out.println("This method have body ");
        }

        //This one dose not
       abstract public  void method2();
    }

In JAVA 8, Interfaces can have static method and default method

interface  Test{
    public static void method(){
        System.out.println("This method must have a body ");
    }

    default void method1(){
        System.out.println("This method must have a body ");
    }
}

and please post the code and the full error message next time