File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes over-riding in java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "over-riding in java" Watch "over-riding in java" New topic

over-riding in java

ksb singh

Joined: Jun 27, 2012
Posts: 2
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

Joined: Aug 16, 2005
Posts: 15092

Welcome to CodeRanch.

Why don't you write a small program to try it out? Experimenting is a great way to learn.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
ksb singh

Joined: Jun 27, 2012
Posts: 2
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

Joined: Aug 19, 2011
Posts: 36
primitive data must be same for all over ridden methods.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46397
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.
I agree. Here's the link:
subject: over-riding in java
It's not a secret anymore!