Professional Documents
Culture Documents
What Is A Class Hierarchy?: Legumes
What Is A Class Hierarchy?: Legumes
It is natural for humans to classify items that have similar properties and behavior into
groups and to even form some type of hierarchy among them. For example, you can have a
broad category like vegetables, and within that you can have a more specific type
like legumes. Within legumes, you can have even more specific types like peas, beans,
lentils, chickpeas, and soybeans for example.
Let's look at how you would represent this relationship in programming terms. If you
make Vegetable a class in Kotlin, you can create Legume as a child or subclass of
the Vegetable class. That means all the properties and methods of the Vegetable class are
inherited by (meaning also available in) the Legume class.
You can represent this in a class hierarchy diagram as shown below. You can refer
to Vegetable as the parent or superclass of the Legume class.
You could continue and expand the class hierarchy by creating subclasses of Legume such
as Lentil and Chickpea. This makes Legume both a child or subclass of Vegetable as well as
a parent or superclass of Lentil and Chickpea. Vegetable is the root or *top-level
(*or base) class of this hierarchy.
Note: Terminology summary
Here is a summary of words used in this codelab and what they mean in the context of Kotlin
classes.
Class hierarchy. An arrangement where classes are organized in a hierarchy of parents and
children. Hierarchy diagrams are usually drawn with the parents shown above children.
Child or subclass. Any class that is below another class in the hierarchy.
Parent or superclass or base class. Any class with one or more child classes.
Root or top-level class. The class at the top (or root) of the class hierarchy.
Inheritance. When a child class includes (or inherits) all the properties and methods of its
parent class. This allows you to share and reuse code, which makes programs easier to understand
and maintain.
For example, there is a View class in Android that represents a rectangular area on the
screen and is responsible for drawing and event handling. The TextView class is a subclass
of the View class, which means that TextView inherits all the properties and functionality
from the View class, plus adds specific logic for displaying text to the user.
Taking it a step further, the EditText and Button classes are children of the TextView class.
They inherit all the properties and methods of the TextView and View classes, plus add
their own specific logic. For example, EditText adds its own functionality of being able to
edit text on the screen.
Instead of having to copy and paste all the logic from the View and TextView classes into
the EditText class, the EditText can just subclass the TextView class, which in turn
subclasses the View class. Then the code in the EditText class can focus specifically on
what makes this UI component different from other views.