r/ProgrammerHumor • • Sep 25 '26

Meme iHatedItUntilITriedIt

Post image
10k Upvotes

540 comments sorted by

View all comments

Show parent comment

0

u/DarthCloakedGuy Sep 25 '26

Huh. Okay.

But what do you do when you need a variable to be able to hold different classes of object?

3

u/HiCookieJack Sep 25 '26

use a new variable?

Create an abstract class

Create an interface

Create a union type

1

u/Less_Independent5601 Sep 25 '26

It depends on the situation and there are many viable solutions. You could use interfaces as example.

Like, if you have a calendar and multiple different types of events that go on a calendar and need some type of function that based on their own unique definition tells you what time it will be and a description of what the event is.

You can make an interface InteractsWithCalendar, or what have you. The interface demands: if you're implementing me, you must follow my contract. The contract could state that you must define a getCalendarDefinition function.

Then, on the different classes that interact with a calendar, you declare they implement the interface, and you give each class their own respective getCalendarDefinition implementation.

Now, if I want to build my calendar, I could define my variables as an array of type InteractsWithCalendar. Now, I know for sure my objects all implement the getCalendarDefinitio function, and I can call that without worries.