[英]Is polymorphism with an interface legal just as how polymorphism with an abstract class is legal?
For example: 例如:
Say you have an abstract class called Animal, and a non-abstract class called Dog. 假设您有一个名为Animal的抽象类和一个名为Dog的非抽象类。 This is legal: 这是合法的:
Animal dog = new Dog();
But if you have an interface called Car and a normal class called Toyota would the same be legal? 但是,如果您有一个名为Car的接口和一个名为Toyota的普通类,那么合法吗?
Car car = new Toyota();
Thanks! 谢谢!
Yes It is legal. 是的,这是合法的。
In your case, Dog must extend Animal: 就您而言,Dog必须扩展Animal:
abstract class Animal {}
class Dog extends Animal {}
The same is true with an interface (which is abstract by definition), and a class which implements it: 接口(根据定义是抽象的)和实现该接口的类也是如此:
interface Car {}
class Toyota implements Car {}
是的,只要丰田实施Car,这当然是合法的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.