Declaring subclasses question. | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
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

1st Jun 2019, 6:09 PM
Robert Atkins
Robert Atkins - avatar
4 ответов
+ 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.
1st Jun 2019, 7:36 PM
Schindlabua
Schindlabua - avatar
+ 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
1st Jun 2019, 6:57 PM
Ipang
+ 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
1st Jun 2019, 7:10 PM
Robert Atkins
Robert Atkins - avatar
+ 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.
1st Jun 2019, 7:15 PM
Ipang