May be this could be silly question but its asked in 3-4 interviews that why following rules are there for overriding:-
Rules 1. If BaseClass having a method whose return type are any primitive-type then while overriding this method, you can't change its return-type.
2. If BaseClass having a method whose return type are any user-defined data-type then while overriding this method, you can keep same return-type or change its return-type by its derived-class.
3. If BaseClass having a method whose thorws a IOException then while overriding you can keep same exception or can change it by its derived-class.
These rules are all to do with the Liskov Subsitution Principle. I'm not going to give a full explanation, but here's an example that demonstrates 2:
Now, if all that was allowed, consider those last two lines. What are the two methods actually returning? Can you see why that would be a problem in one of the cases?
Both methods of Super-Class returning Number. While overriding, methodA() returning same type(Number) but methodB() returning Object which is the superclass of Number which is not allowed.
Same thing i said in my question that we can change return-type by its subclass not by its superclass-type.
That code demonstrates why the rule exists. If you allowed a method to override with a wider or completely different type as return type, then all that code would compile. Which means that on line 16 you'd actually end up assigning an Object to a Number variable. In other words, you've lost type safety. You'd get an error at runtime, but the compiler is supposed to be able to protect you from this.
Whereas on line 15 you end up assigning an Integer to a Number. That's perfectly safe, which shows that overriding to return a subclass of the original return type is safe.
With exceptions the same principle applies. Try writing some code that would be allowed if that rule wasn't in place, and hopefully you'll be able to see the problem it would cause.