I am still learning how to code java and had a question about how inheritance works. 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? If so, how? Thank You. (Sorry if the format sucked)
Asked
Active
Viewed 1,111 times
1
-
A good page explaining different scenario's of inheritance: https://www.geeksforgeeks.org/inheritance-in-java/ – Tom Feb 02 '19 at 12:42
-
I would recommend you to read 'https://self-learning-java-tutorial.blogspot.com/2014/02/types-of-inheritance.html' – Hari Krishna Feb 02 '19 at 12:47
1 Answers
2
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
. 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`.
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.
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:
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
. 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

ernest_k
- 44,416
- 5
- 53
- 99
-
That answers my question, thank you. Are there any examples of which would be preferred in different situations? – Nish Grewal Feb 02 '19 at 12:43
-
@NishGrewal I'm actually editing the post to add examples that illustrate the difference. Will save soon – ernest_k Feb 02 '19 at 12:44
-
-
Let's say you are developing a system that tracks vehicles on a road. You might have a base class for vehicle, subclasses for car and truck, and subsubclasses for specific kinds of cars and trucks. If you were modeling traffic, the subclasses might have characteristics for speeds and lane-changing behavior; if you were modeling road revenue, they might have characteristics for toll passes, height, weight, etc. – arcy Feb 02 '19 at 13:38
-
[this](https://www.oreilly.com/library/view/learning-java-4th/9781449372477/ch06s01.html) is a good link for your question too – Antonino Feb 02 '19 at 13:44