Covariant return in Overriding Methods – Object-Oriented Programming
Covariant return in Overriding Methods In Example 5.2, the definition of the method makeInstance() at (9) overrides the method definition at (3). Click here to view code image // The overridden method in the superclass Light:public Light makeInstance() { … } // (3) Instance method // The overriding method in the subclass TubeLight:@Overridepublic TubeLight makeInstance() { … } // (9) Overriding instance method at (3). Note that the method signatures are the same, but the return type at (9) is a subtype of the return type at (3). The method at (9) returns an object of the subtype Tube-Light, whereas the method at (3) returns an object of the supertype Light. This is an example of covariant return. Depending on whether we call the method makeInstance() on an object of the subtype TubeLight or an object of the supertype Light, the respective method definition will be executed. The code at…
The return Statement – Control Flow
4.13 The return Statement The return statement is used to stop execution of a method (or a constructor) and transfer control back to the calling code (also called the caller or invoker). The usage of the two forms of the return statement is dictated by whether that statement is used in a void or a non-void method (Table 4.2). The first form does not return any value to the calling code, but the second form does. Note that the keyword void does not represent any type. In Table 4.2, the expression must evaluate to a primitive value or a reference value, and its type must be assignable to the return type specified in the method header (§2.7, p. 54, and §5.9, p. 261). See also the discussion on covariant return in connection with method overriding in §5.1, p. 201. As can be seen from Table 4.2, a void method need…