ccc
ccc

Reputation: 370

missing method body abstract class

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

Upvotes: 1

Views: 1497

Answers (5)

Mureinik
Mureinik

Reputation: 311308

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

Upvotes: 2

shikjohari
shikjohari

Reputation: 2288

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

Upvotes: 0

Santhosh
Santhosh

Reputation: 8197

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 :

Upvotes: 4

Adward
Adward

Reputation: 31

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

Upvotes: 0

Eran
Eran

Reputation: 393821

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.

Upvotes: 0

Related Questions