2024年05月20号

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

  • 12
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值