What will be printed when the following code is compiled and run?
class MyBaseClass { public int getCode (){ return 2;} } class MyClass extends MyBaseClass { public long getCode (){ return 3;} } public class Main { public static void main (String [] args) throws Exception { MyBaseClass a = new MyBaseClass (); MyBaseClass aa = new MyClass (); System.out.println (a.getCode ()+" "+aa.getCode ()); }//from w w w. ja v a 2s. co m public int getCode () { return 1; } }
Select 1 option
Correct Option is : D
Class MyClass is trying to override getCode()
method of class MyBaseClass but its return type is incompatible with the MyBaseClass's getCode()
.
When the return type of the overridden method (i.e. the method in the base/super class) is a primitive, the return type of the overriding method (i.e. the method in the sub class) must match the return type of the overridden method.
In case of Objects, the base class method can have a covariant return type, which means, it can return either return the same class or a sub class object.