-5

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

}
Nuki
  • 3
  • 2
  • 1
    `"I get an error because abstract classes cannot have bodies"` -- no the error is not telling you this (because it's not true). Why not show more pertinent code and the actual error message? Perhaps you meant to say "abstract method"? – Hovercraft Full Of Eels Jan 18 '18 at 16:42
  • 1
    *"abstract classes cannot have bodies"* is incorrect, abstract methods cannot have a body, but a abstract class can certainly have non-abstract methods *with* a body. – luk2302 Jan 18 '18 at 16:43
  • *"How can I create an abstract method that generates a random int"* - you can't. It is either `abstract` *or* it does something like generate an int, it cannot both be abstract *and* do something. – luk2302 Jan 18 '18 at 16:44

2 Answers2

0

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.

Maltanis
  • 424
  • 4
  • 13
-1

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

MD9
  • 67
  • 1
  • 6