over-riding in java

ksb singh

Greenhorn

Posts: 2

posted 5 years ago

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.

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

posted 5 years ago

primitive data must be same for all over ridden methods.

Campbell Ritchie

Marshal

Posts: 55668

161

posted 5 years ago

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.