r/learnprogramming • • Apr 05 '22

Name one programming/comp sci concept you never understood and if you understand it, try to explain it to them

Name a programming concept such as virtual functions, pointers, certain algorithms, etc that you always had a hard time understanding and why.

Someone else who reads yours and does understand it, try to explain it to them to help them learn

1.6k Upvotes

738 comments sorted by

View all comments

19

u/[deleted] Apr 05 '22

Casting and upcasting in Java :/

2

u/faceplanted Apr 05 '22

Casting is changing the type of something, languages like java force you to be specific about it by doing things like int x = (int) 1.5, because when you cast things "up", I.e. into less specific types, you have to throw information away, like casting 1.5 to an int means throwing away the .5, and casting 1 to a float means guessing that the rest of the number is .0, which makes sense in that case, but throwing away the .5 for float to int means always rounding down, which is just a decision we made at some point.

This matters in object oriented programming because subclasses are basically their superclasses with data strapped on the end, your Animal class has 3 fields, while your child Cat class has 5? If you want to convert your cat to an animal you have to throw your two extra fields away. If you want to cast an animal to a cat you have to make them up, so it helps to be careful.