1 回答
TA贡献1712条经验 获得超3个赞
可视化这一点的最简单方法是认为继承就像父/子关系。你可以有父 -> 子 -> 孙子等。
当你有:
class A {}
class B extends A{}
class C extends B{}
C就像一个孙子A。这意味着C继承了所有的方法B,包括那些B本身继承自A.
In OOP words,C **is**A` 的方法。
但是,当你有
class A {}
class B extends A{}
class C extends A{}
C和B是兄弟类,这意味着它们都继承了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();
然而,在第二种情况下,当两者都B直接C 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
B但是,和之间没有直接关系C。这些是无效的:
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
添加回答
举报