Skip to main content

Posts

Showing posts with the label Overriding

Method Overriding Rules in Java

1) The signature including the number and type of arguments for the overriding method should be same. 2) The return type should be same. 3) The access modifier should not be more limiting than super class method. 4) The overriding method should not throw exceptions other than those thrown by the method in the superclass.

Can an overriding method have a different return type than the overridden method?

Before Java 5.0, when you override a method, both parameters and return type must match exactly. In Java 5.0, it introduces a new facility called covariant return type. You can override a method with the same signature but returns a subclass of the object returned. In another words, a method in a subclass can return an object whose type is a subclass of the type returned by the method with the same signature in the superclass. For example, the following code compiles and the narrower type B is a legal return type for the getObject method in the subclass, Sub . class A { } class B extends A { } class Super { public A getObject() { System.out.println("Super::getObject"); return new A(); } }