1

There is an error as 'missing method body or declare abstract' of abstract class. But the class WaterLevelObserver is already abstract... how can I fix this error?

abstract class WaterLevelObserver{
    void update(int waterLevel);
}

class SMSWriter extends WaterLevelObserver{
    void update(int waterLevel){
        System.out.println("Sending SMS.. : "+waterLevel);
    }
}

class Alarm extends WaterLevelObserver{
    void update(int waterLevel){
        if(waterLevel>=50){
            System.out.println("ON");
        }else{
            System.out.println("OFF");
        }
    }
}

class Display extends WaterLevelObserver{
    void update(int waterLevel){
        System.out.println("Water level.. : "+waterLevel);
    }
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
ccc
  • 370
  • 5
  • 19

5 Answers5

4

Any un-implemented method inside the abstract class should also be abstract,

so you need to make your method abstract and make sure you implement it in your subclass

  abstract class WaterLevelObserver{
      abstract void update(int waterLevel);
   }

Read the what Oracle says.

See Also :

Community
  • 1
  • 1
Santhosh
  • 8,181
  • 4
  • 29
  • 56
  • @xehpuk Any un-implemented methods inside the `abstract` class should be named as abstract rite ? – Santhosh Feb 06 '15 at 12:08
  • @SanKrish That's right. But abstract classes don't need to have any abstract methods. An example is `java.awt.event.MouseAdapter`. That's also stated in the first sentence of your reference. – xehpuk Feb 06 '15 at 12:09
2

Defining a class as abstract just means that you can't instantiate it and that you're allowed to define abstract methods.

Any method that isn't defined as being abstract must have a body. TL;DR - If you don't want to implement update, define it as abstract:

abstract class WaterLevelObserver{
    abstract void update(int waterLevel);
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

Either you have to define the body or you have to declare it as abstract. If you dont want to add any body - change

 void update(int waterLevel);} 

to

`abstract void update(int waterLevel);}`
shikjohari
  • 2,278
  • 11
  • 23
0

The method should be abstract too:

abstract class WaterLevelObserver
{
    void abstract update(int waterLevel);
}

A method that is not declared as abstract must be implemented by the class, even if it's in an abstract class.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

We need to explicitly tell compiler that its a abstract class in the case of abstract class.without the keyword it will search for body. its fine in case of interface as by default all are abstract.

abstract void update(int waterLevel);

Adward
  • 31
  • 5