Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract method implementation (if unused)

Tags:

java

For instance, I have an abstract class implemented like this:

public abstract class Animal
{
   public abstract void makeNoise();
}

and I have a child class which is representing an animal that does not make any noise. Which is better?

public class Turtle extends Animal
{
   // properties and methods
   public void makeNoise()
   {
     //leave it empty
   }
}

or should i simply make it : public abstract void makeNoise(); inside Turtle?

like image 225
Erail Avatar asked Dec 04 '22 21:12

Erail


1 Answers

It is better to move the makeNoise() method out of Animal as all the animals doesnot make noise. So create another interface NoiseMaker and add the the makeNoise method inside that.

public abstract class Animal {
  // animals methods
}

public interface NoiseMaker {
   void makeNoise();
}

public class Turtle extends Animal {
   // properties and methods which are applicable for turtle
}

And when you want an animal which makes noise like Lion you can extend Animal class and implement NoiseMaker, so that it has the behaviour of Animal as well as it makes noise.

public class Lion extends Animal implements NoiseMaker {
    public void makeNoise() {
        // implementation
    }

    // other properties and methods which are applicable for turtle
}
like image 111
Johny Avatar answered Dec 11 '22 17:12

Johny