Q.1 Do the overriding methods must have the same return type(or sub-type)?
· Form java 5.0 onward it is possible to have different return types for an overriding method in the child class. but child return type should be sub-type or parents return type.
§ This phenomenon is known as | convenient return type.
Example:-
class Test
{
object show()
{
System.out.println(“one”);
return null;
}
}
class Test1
extends Test {
String show() {
System.out.println(“one”);
return null;
}
public static void main(String args[])
{
Test t
= new Test();
t.show();
Test1 t
= new Test1();
T1.show();
}
}
Ø Before JDK 5.0
it was not possible to vary a method by changing the return type.
Ø Java 5.0 onward
it is possible to have different return types for an overloading method in child
class but child return type should be a subtype of a parents return type
overriding method become variant with respect to return type .so this is known as correct return type.
Q.2 Overriding and Access-modifier?
Ø The access modifier for an overriding method can allow
more but not less, access than the overridden method.
Example:- a protected
instances method in the superclass can be made public but not private in the
subclass doing so will generate a compile-time error.
class Test
{
protected/default/ public
void show() {
System.out.println(“one”);
}
}
class Test1
extends Test {
public void show() {
System.out.println(“one”);
}
public static void
main(String args[]) {
Test t
= new Test();
t.show();
Test1 t
= new Test1();
T1.show();
}
}
0 Comments