• Post Reply Bookmark Topic Watch Topic
  • New Topic

Returning a Class or Interface:  RSS feed

 
Ranch Hand
Posts: 151
Java MyEclipse IDE Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i was studing webpage and get bellow information but can't understand this can anyone illustrate this?


When a method uses a class name as its return type, such as whosFastest does, the class of the type of the returned object must be either a subclass of, or the exact class of, the return type. Suppose that you have a class hierarchy in which ImaginaryNumber is a subclass of java.lang.Number, which is in turn a subclass of Object, as illustrated in the following figure.


Now suppose that you have a method declared to return a Number:
public Number returnANumber() {
...
}
The returnANumber method can return an ImaginaryNumber but not an Object. ImaginaryNumber is a Number because it's a subclass of Number. However, an Object is not necessarily a Number — it could be a String or another type.
You can override a method and define it to return a subclass of the original method, like this:

public ImaginaryNumber returnANumber() {
...
}
This technique, called covariant return type, means that the return type is allowed to vary in the same direction as the subclass.
Note: You also can use interface names as return types. In this case, the object returned must implement the specified interface.
 
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, you can create an object and assign it to the super class/interface reference.
for example: InputStream is = new FileInputStream("c:\\test.txt");

Second, read this thread
 
Ranch Hand
Posts: 297
Eclipse IDE Firefox Browser Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is one of best design practice we follow "Programming for interface than implementation" , you can read detail in Head first Design pattern. advantage is that the code will be more maintainable because due to polymorphism a super class reference can hold any subclass reference. So in future if you create a modified subclass you need not have to change your client code.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!