Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP 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
Pie
Posts: 15438
41
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
Pie
Posts: 49776
69
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic