Suppose you have two methods, one that works on Cat objects and one that works on Dog objects:
Suppose you want to replace this with one method. The classes Cat and Dog need to have a common supertype (class or interface), and you would write the method to work on the supertype:
You can make it more type-safe with generics. In principle, the method above could return a List of other kinds of animals than the kind of animal that you pass to it. That would be strange - imagine a Dog having a list of Cats as its babies... So you could do this:
The return classes don't need to have a common super class or interface as long as you can cast them to or populate another object with the appropriate values. If you wanted to implement something like this you could use the following as a guide:
This approach would work well with primitive types. With more complex objects that you have control over, making them extend a common class or implement a common interface would be a better approach. Some sample code of what you're trying to do would be helpful.
a method has to be defined to return one kind of thing. you can't have a method sometimes return an int and sometimes return a String, as it would be difficult if not impossible for the calling code to know what to do. How would it know what to use to store the return value?
You can't do that. especially since the method may not know what to return until after it's been entered
but you can do this:
Now it doesn't matter. No matter what you return, it's a ParentClass object. You could do something similar by defining an interface and having your ChildA and ChildB implement the interface.
subject: Design single method with different input type and different data type