我仍在学习如何编写Java代码,并对继承的工作方式有疑问。类A是父类,类B是从类A继承所有方法的子类。假设我创建了第三个类C,如果我对类C进行了类B扩展,则与对类C进行类A扩展有所不同?如果是这样,怎么办?谢谢。 (很抱歉,如果格式吸入)
答案 0 :(得分:2)
最简单的可视化方法是考虑继承就像父/子关系。您可以拥有“父母”->“孩子”->“孙子”等。
如果有:
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