class Person { void f() {} }
class Student extends Person { void f() {} }
So when I execute the following code:
Person p = new Student();
((Person) p).f();
Why is the f() function in the Student class called when the variable is cast as a Person? I understand why the f() function is called when it is just p.f(), but I guess I’m just confused to what exactly the cast does.
This is one of the cornerstones of Object Oriented: Polymorphism. You have all kinds of Person entities each doing f() in its own way! It is the actual instance of the object and not what you cast it to that does f().