You are most probably confusing inheritance with composition.
In inheritance, a child class is a parent class (and more). It is produced with the extends
keyword, as in the following code :
class Dog extends Animal { /*...*/ }
The Dog
is an Animal
and as such will inherit the parent class' public and protected methods, maybe such as feed()
, breed()
, etc. It can define other methods specific to the child class such as bark()
.
This direction must be unidirectional, if a class A
extends a class B
, the class B
can't extend the class A
(their definition would recurse into an infinite loop : "What is a Dog
? Well, to begin with, it's an Animal
; alright, what is an Animal
? Well to begin with, it's a Dog
, etc.")
In composition, a class has a reference to an instance of another class. It is produced by using fields that reference instance of other classes, such as in the following code :
class Kennel {
Director director;
Set<Dog> dogs;
//...
}
A Kennel
has a Director
and a set of Dog
s.
In this case the relation between both classes can be bi-directional (a Dog
can have a Kennel
field) without any problem, and the relation actually isn't between classes but rather between instances (except if your fields are static
, but let's not bother with that).