• Post Reply Bookmark Topic Watch Topic
  • New Topic

Overloading Vs. Overriding [From "Jeanne Boyarsky" OCAJP book]  RSS feed

 
jnrohit Jain
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look at the following code sample from "Jeanne Boyarsky" OCAJP book:

Filename: Bird.java

Filename: Eagle.java


Following is the statement written in this book and I do not understand the highlighted part:-

The second method, eat(), is overridden in the subclass Eagle, since the signature is the
same as it is in the parent class Bird- they both take a single argument int. Because the
method is being overridden, the return type of the method in Eagle must be a subclass of
the return type of the method in Bird
. In this example, the return type of void is not a sub-
class of int. therefore, the compiler will throw an exception on this method definition.
 
Igor Soudakevitch
Author
Ranch Hand
Posts: 38
7
Android Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It does not have to be a subtype; consider it a small typo. Look at the Rule #4 at the top of the same page 248:

If the method returns a value, it must be the same or a subclass of the method in the parent class, known as covariant return types.

You can check this rule by changing the declaration of the method eat() in Bird by replacing void with int; just add an appropriate return statement --- and you'll see that the class Eagle will compile. Also you can add the @Override annotation to eat() in Eagle, and the compiler won't object to it.

HTH.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!