基于 this answer 末尾的注释看起来子类型化和继承在 Java 中是截然不同的概念。它是什么?仅当类声明包含 extends ...
子句时才继承吗?如果是这种情况,那么一个类将不会继承自 Object,即使它是它的子类型,对吧?
最佳答案
继承是实现子类型化的一种方式。取自Wikipedia :
In programming language theory, subtyping (also subtype polymorphism or inclusion polymorphism) is a form of type polymorphism in which a subtype is a datatype that is related to another datatype (the supertype) by some notion of substitutability, meaning that program elements, typically subroutines or functions, written to operate on elements of the supertype can also operate on elements of the subtype.
简而言之,让我们看一下:
class Super {
}
class Child extends Super {
}
这就是继承,因为 Child
继承了 Super
的一切。
Super super = new Child();
这是子类型化,因为我们引用Child
作为Super
。所以当我说继承允许您执行子类型化时,您应该明白我的意思,但它们不是一回事。
例如,您可以通过接口(interface)实现子类型化:
class Child extends Super implements ISomeInterface {
}
现在我们可以将 Child
称为:
ISomeInterface someInterface = new Child();
在这里,我们将其称为 ISomeInterface
类型,不需要继承关系。
您的问题
Java 中的所有Objects
都是Object
类型的子类。它们隐式地在它们的类 header 中有extends Object
。这就是语言的工作方式。所以是的,每个对象都是 Object
类的子类型。
在 Java 中,继承只能通过使用 extends
关键字来实现。
额外阅读
Liskov Substitution Principle是一个非常注重子类型概念的设计原则
The different relationships Java类之间。这将帮助您更深入地了解 OOP。
编辑
聆听 Marko Topolnik 所说的一切。你知道,他很聪明。
关于JAVA:子类型和继承的概念是一回事吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25552730/