Can overridden methods have different return types?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
The return type must be the same as, or a subtype of, the return type declared in the original overridden method in the superclass.
Java supports* covariant return types for overridden methods. This means an overridden method may have a more specific return type. That is, as long as the new return type is assignable to the return type of the method you are overriding, it's allowed.
For example:
This is specified in section 8.4.5 of the Java Language Specification:
("|R2|" refers to the erasure of R2, as defined in §4.6 of the JLS.)
* Prior to Java 5, Java had invariant return types, which meant the return type of a method override needed to exactly match the method being overridden.
yes It is possible.. returns type can be different only if parent class method return type is
a super type of child class method return type..
means
If this is the then different return type can be allowed...
Yes, if they return a subtype. Here's an example:
This code compiles and runs.
Broadly speaking yes return type of overriding method can be different. But its not straight forward there are some case involved in this.
Case 1: If the return type is primitive data type or void.
Output: If the return type is void or primitive then the data type of parent class method and overriding method should be same. e.g. if return type is int, float, string then it should be same
Case 2: If the return type is derived data type:
Output: If the return type of the parent class method is derived type then the return type of the overriding method is same derived data type of sub class to the derived data type. e.g. Suppose i have a class A B is subclass to A C is subclass to B D is subclass to C then if if the super class is returning type A then the overriding method is subclass can return A, B, C or D type i.e its sub types. This is also called as covarience.
YES it can be possible