Difference between object creation syntax(对象创建语法的区别)
问题描述
请解释一下对象一和对象二的区别:
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.
这篇关于对象创建语法的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对象创建语法的区别


- Eclipse 的最佳 XML 编辑器 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 获取数字的最后一位 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 转换 ldap 日期 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01