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 :/

18

u/procrastinatingcoder Apr 05 '22

All dogs are animals, not all animals are dogs. Logically you can go one way, not the other.

More specifically, I'm not sure of what bytecode gets generated for the JVM, but as far as C++ and a few other compiled languages go, what "inherited" classes do is just "copy" the inherited code with their own code right beside it. So you can always refer to something you copied, but you can't generate the missing pieces afterwards.

2

u/paulstelian97 Apr 06 '22

For the bytecode, upcasting is essentially a no-op or assignment. Down casting involves a manual dynamic type check (and throwing an exception if the check fails) followed by a simple assignment (or a no-op again)

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.

1

u/GxK1999 Apr 05 '22

Casting i.e.:

double a = 3.0;

int b = a; //throws error because float type cannot be assigned to an int, therefor you need to cast it.

int b = (int) a; //output: 3