aspose file tools*
The moose likes Beginning Java and the fly likes Making Method Abstract From Concrete Method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Making Method Abstract From Concrete Method" Watch "Making Method Abstract From Concrete Method" New topic
Author

Making Method Abstract From Concrete Method

Craig Oliver
Greenhorn

Joined: Aug 25, 2003
Posts: 21
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

Joined: Jul 08, 2003
Posts: 24184
    
  34

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."


[Jess in Action][AskingGoodQuestions]
sever oon
Ranch Hand

Joined: Feb 08, 2004
Posts: 268
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Making Method Abstract From Concrete Method