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

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

问题描述

请解释对象1和对象2之间的区别:

Please explain the difference between object one and two:

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

类欧宝扩展了类车。

推荐答案

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

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

one = new Ford(...);

但你不能重新分配两个之类的因为它仅限于欧元

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();

因为它知道两个仅限于 opel ,因此它知道方法 m 将存在。

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

通常,您希望将变量声明为最广泛类型。也就是说,如果你只想在 car 中使用方法,那么用类型 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.

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

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天全站免登陆