Kristian Vukusic
Kristian Vukusic

Reputation: 3324

return a specific type when Object is the return type in a method in Java

I have a method getValue like this

public Object getValue() {
     return Integer.valueOf(0);

}

and a call in the main method:

getValue() + 5;

This is simplified.

How to get this working without casting in the main method, but instead how to cast the return type if possible?

Upvotes: 2

Views: 16115

Answers (3)

Eric Levine
Eric Levine

Reputation: 13554

You could use generics:

public class MyClass<T extends Number>{


  public T getValue(){
    //do something here
  }
}

MyClass<Integer> foo = new MyClass<Integer>();
foo.getValue()+5;

Upvotes: 8

lrAndroid
lrAndroid

Reputation: 2854

If your method returns an Object, you're going to have to cast at some point or another to use the class specific functions of Integer, Double, etc.

Upvotes: 2

srisris
srisris

Reputation: 569

I guess you should not do that, if you wrote this function public Object getValue() then why not change it to public Integer getValue() and return Integer.

If you also expect other types then over load the method public String getValue(), public Double getValue() etc. Use factory pattern to decide which method to call.

If you dont want to cast then you can't use Object as return type and still use getValue() + 5;

I also like elivine's response

Upvotes: 0

Related Questions