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

时间:2019-02-02 12:35:55

标签: java inheritance subclass superclass

我仍在学习如何编写Java代码,并对继承的工作方式有疑问。类A是父类,类B是从类A继承所有方法的子类。假设我创建了第三个类C,如果我对类C进行了类B扩展,则与对类C进行类A扩展有所不同?如果是这样,怎么办?谢谢。 (很抱歉,如果格式吸入)

1 个答案:

答案 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{}

CB兄弟类,这意味着它们都继承了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