LEGAL RETURN TYPE

You have to remember the following rules for returning a value:
1. You can return null in a method with an object reference return type.
public Button doStuff() {
return null;}
2. An array is a perfectly legal return type.
public String[] go() {
return new String[] {"Fred", "Barney", "Wilma"};
}
3. In a method with a primitive return type, you can return any value or
variable that can be implicitly converted to the declared return type.
public int foo() {
char c = 'c';
return c; // char is compatible with int
}
4. In a method with a primitive return type, you can return any value or
variable that can be explicitly cast to the declared return type.
public int foo () {
float f = 32.5f;
return (int) f;
}
5. You must not return anything from a method with a void return type.
public void bar() {
return "this is it"; // Not legal!!
}
6. In a method with an object reference return type, you can return any
object type that can be implicitly cast to the declared return type.
public Animal getAnimal() {
return new Horse(); // Assume Horse extends Animal
}
public Object getObject() {
int[] nums = {1,2,3};
return nums; // Return an int array,
// which is still an object
}
We can declare an interface as return type,
public interface Chewable { }
public class Gum implements Chewable { }
public class TestChewable {
// Method with an interface return type
public Chewable getChewable() {
return new Gum(); // Return interface implementer
}}
ABSTRACT CLASS CAN ALSO BE RETURN TYPE OF METHOD
public abstract class Animal { }
public class Bear extends Animal { }
public class Test {
public Animal go() {
return new Bear(); // OK, Bear "is-a" Animal
}}

No comments:

Post a Comment