[英]Subtyping without inheritance and inheritance without subtyping?
我的老师发布了一个期中示例供我们执行,我对以下问题感到困惑:
显示不带子类型的继承和不带子类型的继承的示例。
我们使用以下定义,并且使用Java进行编程: http : //www.cmi.ac.in/~madhavan/courses/pl2006/lecturenotes/lecture-notes/node28.html
代表这两个想法的好方法是什么?
根据列出的子类型定义:
子类型化是指接口的兼容性。 如果可以在类型A的对象上调用的每个函数也可以在类型B的对象上调用,则类型B是A的子类型。
Java中的子类型基本上类似于在Java中扩展或实现接口。 例如:
interface Fish {
void swim();
}
interface FlyingFish extends Fish {
void fly();
}
在这里, FlyingFish
是Fish
的子类型,因为飞鱼始终是鱼的一种。
按照列出的继承定义:
继承是指实现的重用。 如果B的某些功能是根据A的功能编写的,则B将从另一种A继承。
此定义继承是指Java中的实现继承。 这通常也是子类型化的一种形式,但并非总是具有设计不佳的分类法,您在职业发展中会看到这种分类法。 ;-) 例如:
class FlyingFish {
void swim() {
// implementation code to swim in water
}
void fly() {
// implementation code to jump out of the water and fly
}
}
class Bird extends FlyingFish {
// no need to implement fly, reuse implementation of flying fish
void swim() {
// do nothing implementation - most birds can't swim.
}
}
class Fish extends FlyingFish {
void fly() {
// do nothing implementation - most fish can't fly.
}
// no need to implement swim, reuse implementation of flying fish
}
在这里,无论是Bird
和Fish
不适当继承FlyingFish
,即使没有Bird
,也不Fish
是子类型的鳐鱼。
希望有帮助,如果您有任何后续问题,请发表评论。 另外,《 Effective Java 2nd Ed》是一本值得一读的书。 乔什·博奇(Josh Boch) 在这本书中,Bloch在这些主题上提供了一些非常好的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.