Abstract method implementation that does nothing

joshft91 :

I'm not quite sure how to word this question, but hopefully the example will make it a bit more clear. I'm trying to figure out the best way to have one of the implemented abstract methods not be called (do nothing) and I'm curious if my current approach is at all somewhat right.

abstract class Vehicle {
  void doSomething() {
    if (this.getClass() instanceof Chevy) {
      operateOnCar();
    }
  }
  abstract void operateOnCar();
}

class Chevy extends Vehicle {
  @Override
  void operateOnCar() {
    print("Doing something to a car")
  }
}

class HarleyDavidson extends Vehicle {
  @Override
  void operateOnCar() {
    throw Exception("This isn't a car")
  }
}

The other approach I can think of is to have the HarleyDavidson class implement operateOnCar()but do absolutely nothing - i.e. an empty method body. Is that potentially better? Maybe neither of these are viable examples and I should reconsider my design. Thanks!

Edit: tried to make my example a bit more clear

John Bollinger :

I'm trying to figure out the best way to have one of the implemented abstract methods not be called (do nothing)

Asserting that a method should not be called is totally different from asserting that it should do nothing. It is furthermore wrongheaded to define a method on the superclass, regardless of abstractness, that is not ok to call on any instance of any subclass. Thus, some variation on the "do nothing" alternative is a much better choice.

And what's so hard about a method doing nothing when it does not need even to provide a return value? This is a method that does nothing:

void isCar() {
    // empty
}

I should also observe at this point a method named isCar would be expected by most Java programmers to return a boolean indicating whether the object on which it is invoked is a "car", whatever that means in context. It would come as a surprise that such a method is declared not to return anything, and perhaps an even bigger surprise that it writes to System.out.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=87664&siteId=1