对象创建语法的区别 [英] Difference between object creation syntax

查看:28
本文介绍了对象创建语法的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请解释一下对象一和对象二的区别:

Please explain the difference between object one and two:

    car one = new opel();    
    opel two = new opel();  

欧宝级扩展了汽车级.

推荐答案

您可以将 one 重新分配给 car 的某个其他子类的对象:

You could reassign one to an object of some other subclass of car:

one = new Ford(...);

但是您不能像那样重新分配 two,因为它被限制为 opel.

But you can't reassign two like that, since it's restricted to being an opel.

如果 m 是在 opel 类中定义的方法,而不是在 car 类中定义的方法,那么编译器会在以下情况下给您一个错误你这样做:

If m is a method that's defined in the opel class but not the car class, then the compiler will give you an error if you do this:

one.m();

但这没关系:

two.m();

因为它知道 two 被限制为 opel,所以它知道方法 m 会存在.

since it knows two is restricted to being an opel, so it knows that method m will exist.

通常,您希望将变量声明为可能的最广泛类型.也就是说,如果你只打算使用 car 中的方法,那么用 car 类型声明它(就像你对 one 所做的那样),因为你告诉读者算法只需要知道 one 是一个 car,它不需要知道它是什么类型的汽车.

Generally, you want to declare your variables to be the broadest type possible. That is, if you're only going to use methods in car, then declare it with type car (like you did with one), because you're telling the reader that the algorithm only needs to know that one is a car, it doesn't need to know what kind of car it is.

更多:有必要了解变量同时具有编译时类型运行时类型.编译器将 one 视为 car,因为它不知道在任何给定时间变量将是哪种类型的 car.但是两者的运行时类型都是opel.如果您有一个为 car 定义的方法 mm,然后为 opel 覆盖,则 <​​code>one.mm() 和 two.mm() 都将调用 same 方法.一旦编译器查看编译时类型并确定调用是合法的,那么当程序运行时调用哪一个取决于运行时类型.

More: It's necessary to understand that a variable has both a compile-time type and a runtime type. The compiler sees one as a car, because it doesn't know what kind of car the variable will be at any given time. But the runtime type of both will be opel. If you have a method mm that is defined for car, and then overridden for opel, one.mm() and two.mm() will both call the same method. Once the compiler looks at the compile-time type and decides the call is legal, then which one gets called when the program is run depends on the runtime type.

这篇关于对象创建语法的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆