是否可以创建一个从另一个子类扩展的子类?

Is it possible to create a subclass which extends from another subclass?

我仍在学习如何编码 java 并且对继承的工作原理有疑问。 Class A 是父级 class,Class B 是子级 class,它继承了 Class A 的所有方法。假设我创建了第三个 class, Class C。如果我做 Class C extends Class B,这与做 Class C extends Class A 有什么不同吗?如果是这样,如何?谢谢你。 (抱歉,格式很烂)

最简单的可视化方法是将继承视为 parent/child 关系。你可以有 Parent -> Child -> Grand Child,等等

当你有:

class A {}
class B extends A{}
class C extends B{}

C 就像 A 的盛大 child。这意味着 C 继承了 B 的所有方法,包括 B 本身继承自 A. In OOP words,C**is**A` 的那些方法。

但是,当您有

class A {}
class B extends A{}
class C extends A{}

CBsibling 类,这意味着它们都继承了 A 的方法,但它们是彼此不兼容。


在第一种情况下,这些是有效的:

C c = new C();
c.methodFromA(); //C inherits methods from A by being its grand-child
c.methodFromB(); //C inherits methods from B by being its child
c.methodFromC();

然而,在第二种情况下,当 BC extends A 直接:

C c = new C();
B b = new B();
c.methodFromA(); //C inherits methods from A by being its child
b.methodFromA(); //B inherits methods from A by being its child

c.methodFromB(); //not allowed
b.methodFromC(); //not allowed

但是,BC 之间没有直接关系。这些无效:

B b = new B();
C c = new C();

b = (B) c; //invalid, won't compile

A b = b;
c = (C) b; //will compile, but cause a ClassCastException at runtime