View RSS Feed

Java Object

Returning a Class or Interface

Rate this Entry
by , 04-26-2012 at 05:39 PM (2332 Views)
When a class name is used by a method as its return type, like whosFastest would be doing, typeís class of returned objects shall be subclass or exact class of return type. Letís say that class hierarchy is there where java.lang.Number has a subclass ImaginaryNumber that is also the Objectís subclass that has been illustrated in figure given below:

Name:  1.jpg
Views: 316
Size:  3.1 KB

ImaginaryNumberís class hierarchy

Letís say a method has been declared so that a Number could be returned:

Java Code:
public Number returnANumber() {
An ImaginaryNumber could be returned by the returnANumber method, but not an Object. ImaginaryNumber is considered to be a Number as it is Numberís subclass. But an Object is not always a Number ó it can be another type or string.

A method can be overridden and could be defined to return original methodís subclass, this way:

Java Code:
public ImaginaryNumber returnANumber() {
Technique which is known as covariant return type means that it is permitted that the return type can vary in the similar direction just like the subclass.

Submit "Returning a Class or Interface" to Facebook Submit "Returning a Class or Interface" to Digg Submit "Returning a Class or Interface" to Submit "Returning a Class or Interface" to StumbleUpon Submit "Returning a Class or Interface" to Google