0
Declaring subclasses question.
What are the benefits of declaring a subclass like so Superclass a = new Subclass() As opposed to Subclass a = new Subclass() Is the difference solely in the fact that the first example more clearly demonstrastes to other readers of our code the Subclass is derived from Superclass? Or are there actual performance/System benefits from doing it this way
4 Answers
+ 3
There's not really a point, but if you send your `a` off to a function that needs an object of type `Superclass` you might aswell declare it that way.
I think Ipang gave a good usecase. But I think it's just personal preference even in that case.
I have definitely used an `ArrayList` in a function before and then returned it as just a `List`, because it seemed like the person using the function doesn't need to know which kind of List I used. Like it's a useless implementation detail.
But again that's just preference I think.
+ 2
I remember seeing this topic before, and if I understood the response correctly, that comes useful when we have defined a collection of `Superclass` type. And by using that
method for instantiation we can store any instance of any class that had extended `Superclass`.
It is possible that I might have misunderstood the response back then though, so I guess it's safer to wait for the experts' opinion đ
Hth, cmiiw
+ 2
Ipang maybe, however i believe if you define a collection of type superclass, it will take any sub class of said super no matter how the instance variable is declared. Though it has been a while since ive worked with that specific scenario
+ 2
Yes Robert Atkins, I'm waiting for someone more knowledgeable to come and say something, it isn't all too clear to me either.