如果一个类实现一个接口,并被分配给具有该接口类型的变量,那么该对象是什么类型? [英] If an class implements an interface, and is assigned to a variable with a type of that interface, what type is that object?
本文介绍了如果一个类实现一个接口,并被分配给具有该接口类型的变量,那么该对象是什么类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public class Motor implements Measurable {
...
}
public Measurable motorTemperature = new Motor();
对象motorTemperature
的类型是什么?是电动机,可测量的还是两者兼而有之?
What is the type of the object motorTemperature
? Is it Motor, Measurable, or both?
推荐答案
即使将对象分配给静态类型为接口Measurable
的变量,该对象的运行时类型仍为Motor
.类型定义行为,而接口定义无需强制转换即可调用的方法.
The runtime type of the object remains Motor
even when you assign it to the variable statically typed as the interface Measurable
. The type defines the behavior, while the interface defines which methods you can call without a cast.
这篇关于如果一个类实现一个接口,并被分配给具有该接口类型的变量,那么该对象是什么类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文