Core: Casting Objects
So the goal of this video is to be able to walk through those decisions that compile time and runtime and also be able to cast objects.
背景:
Where we left off in the last video, was we had just done this example. Where we attempted a call to getSID method on a Student object, but we were unable to because s is a person reference.
What we'd like to be able to do is tell the compiler, hey I know this is gonna be a student at runtime, could you let me call this method? The way you do that is casting.
Now I can't stress this enough. You have to be careful when you narrow. The reason why is because you're telling the compiler to trust you. You're saying trust me, compiler, I know this is gonna be a Subclass reference at runtime. And then the compilers gonna believe you and then you're gonna try to do this at runtime.
What would be really great is if we could just test this. Say, is this a student? Before I do the cast. And the way we can do this is using an operator instanceof. So this performs a runtime check of whether or not there is a relationship. So if you say s instanceof Student, what it's gonna do is gonna check, is s an instance of a Student.
Or does s is a relationship with Student at runtime? Now if you do this check with a conditional, you'll then be able to only execute this when it actually is a Student object.
At this point, with the Compile Time Decisions we've discussed and the Runtime decisions we've discussed, polymorphism should make a great deal of more sense :)