Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

over-riding in java

 
ksb singh
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am following head first java. The book states that for a method to be overriden in a subclass- it must have the same argument list though it can have a compatible return type. I understand that if the return type in superclass is animal and that in subclass is Dog , then it will be a valid over-ride(assuming dog extends animal). But is the same thing valid for primitives as well.
Can i declare the superclass method with return type "int" and the subclass one with "byte" since byte is a valid int.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15276
38
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to CodeRanch.

Why don't you write a small program to try it out? Experimenting is a great way to learn.
 
ksb singh
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
well i just did, and the answer is no, but what i would like to know is there no scenario in which an overloaded method returns a primitive different from the primitive returned by the superclass method..
 
Bharat Kasodariya
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
primitive data must be same for all over ridden methods.
 
Campbell Ritchie
Sheriff
Posts: 48930
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That rule changed about 8 years ago. In Java1.0 to Java1.4.2, the return type of an overriding method had to be the same as that of the overridden method. In Java5, they introduced “covariant return types”, which meant that the return type had to be a subtype of the overridden method’s return type.
Primitives don’t have subtypes, so you can’t change primitive return types.
Reference types may have other types which extend them, but you can consider any reference type to be a subtype of itself.The subtypes of Foo there are Foo, Bar and Baz, and the proper subtypes of Foo are Bar and Baz. The links are from the Java™ Language Specification; they are by no means easy to read.
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic