[英]Is it possible to create a subclass which extends from another subclass?
I am still learning how to code java and had a question about how inheritance works. 我仍在学习如何编写Java代码,并对继承的工作方式有疑问。 Class A is the parent class and Class B is the subclass which inherits all the methods from Class A. Suppose I create a third class, Class C. If I do Class C extends Class B, is this different than doing Class C extends Class A? 类A是父类,类B是从类A继承所有方法的子类。假设我创建了第三个类C,如果我对类C进行了类B扩展,则与对类C进行类A扩展有所不同? If so, how? 如果是这样,怎么办? Thank You. 谢谢。 (Sorry if the format sucked) (对不起,如果格式很烂)
The simplest way to visualize this is to consider that inheritance is like a parent/child relationship. 可视化的最简单方法是考虑继承就像父/子关系。 You can have Parent -> Child -> Grand Child, etc. 您可以有“父母”->“孩子”->“孙子”等。
When you have: 当你有:
class A {}
class B extends A{}
class C extends B{}
C
is like a grand child of A
. C
像是A
的孙子。 And that means C
inherits all the methods from B
, including those methods that B
itself inherited from A. In OOP words,
C **is**
A`. 这意味着C
将从B
继承所有方法,包括B
本身从A. In OOP words,
继承的那些方法A. In OOP words,
C **is**
A`。
However, when you have 但是,当你有
class A {}
class B extends A{}
class C extends A{}
C
and B
are sibling classes, meaning they both inherit A
's methods, but they are incompatible with one another. C
和B
是同级类,这意味着它们都继承A
的方法,但是彼此不兼容。
In the first case, these are valid: 在第一种情况下,这些是有效的:
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();
In the second case, however, when both B
and C
extends
A
directly: 但是,在第二种情况下,当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
However, there's no direct relationship between B
and C
. 但是, B
和C
之间没有直接关系。 These are invalid: 这些是无效的:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.