Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Making Method Abstract From Concrete Method

 
Craig Oliver
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It appears you can make a method abstract in the subclass even though it has been made concrete in super class. What would benefit of this be?
Below compiles okay
class A
{
short m2()
{
return (short) 420;
}
} // End class A
abstract class B extends A
{
abstract short m2();
} // End class B
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, same as the benefit from defining any other abstract method: you force subclasses to implement the method. I can't think of a simple example of a situation where you'd want to do this, although it's easy enough to come up with a complicated one. I think in this particulat case it wasn't a matter of anyone saying "one should be able to do this" when designing Java, but more a matter of not seeing any significant reason for saying "one shouldn't be able to do this."
 
sever oon
Ranch Hand
Posts: 268
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is very interesting, and something I hadn't known before I read your question. Even so, though, I can see why it's allowed. If you think about it in terms of design-by-contract, a class defines a method and the contract for that method. A subclass may decide to define a more restrictive contract for that method (the only thing any subclass should ever do when overriding a method, by the way), but that more restrictive contract can't be defined concretely by that class itself.
If you think about this in terms of objects, it makes sense...every abstract class in Java extends java.lang.Object, a concrete class. Why shouldn't the same be true of methods? Now that I know this, it will come in handy if I ever find the equals() method defined by Object inadequate and want to force subclasses to override it. Or let's say I override equals(), but for some odd reason I must defer overriding of hashCode() (which should always be overridden with equals()) to subclasses. I could simply document that subclasses should override hashCode()...or, I could force them to do so explicitly by overriding Object.hashCode() to make it abstract.
sev
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic