I think that in this case, this example does more harm than good. To do any Circle
or Shape
related operations you will need to cast your current object. Other than adding potential overhead, this could lead to issues such as incompatible types.
Doing generic programming is usually recommended since it allows your code to be flexible. Unlike the example you have posted however, it is recommended only when done right. Creating everything as an object will almost always do more harm than good.
Taking the List
as an example, if you where to have a method which returns an ArrayList<String>
as a result: public ArrayList<String> foo()
, then, you are bound to that particular type. If you want a linked list, you will probably need to write some sort of converter which creates a LinkedList<String>
from an ArrayList<String>
.
On the other hand, if you use the generic interface instead, your method would become something like so: public List<String> foo()
. This will allow who ever consumes foo
to be able to create any one of the data structures which implement the List
interface without the need of going through hoops.
EDIT: As per your comment, most of the time it does not help. As I mentioned in my answer it does more harm than good. One of the instances where working with objects makes sense is the readObject()
method provided by the ObjectInputStream
. This method is used when you are reading a custom object, which the ObjectInputStream
does not know about. Since in Java everything extends the Object
class, this method yields an object. Even then, every illustration I have seen of this method they eventually cast it to something else.