What You Need to Know About Inheritance in Java

Cloudage
Java is an object-oriented programming language, and one of the most crucial concepts in this is a thing called inheritance. In this article I will explain the basics of inheritance in Java.

As the name suggests, inheritance is a mechanism that lets one class inherit the behavior and attributes of another class. This means that you can have an existing class, and then just by indicating how a new class is different that the original class, you have created a new class. It makes creating new classes so easy!

Inheritance follows a very strict hierarchy, where the class that inherits from another class is called a subclass. The class that gives the inheritance is called a superclass.

To any one class there can only be one superclass. Think of this as where you inherited certain traits from your parents. You only have one set of parents. There can however be an unlimited number of subclasses to a class. This is where you can have many siblings, who all inherited traits for the same set of parents. The terms superclass and subclass are very important to learn, and to understand.

Just to be sure that the concept of inheritance is understood I'll bring on one more example. Let's say that you have created a class for your Java program, but you need another class that have some of the same attributes as your first class. You do not have to copy the desired code over to this new class, all you have to do is to make the class a subclass of the first class. The subclass then receives all those attributes and behavior, all you have to worry about is in what ways the subclass should be different.

Working with class hierarchy where you create subclasses who then become superclasses to new subclasses takes a lot of planning and thinking ahead. You need to set up a diagram over which classes do what, and what behavior/attributes are inherited from each superclass.

If there is a behavior that you need for several classes, put that behavior into a superclass and subclass all the classes that needs that specific behavior. If there is later a need to change the behavior in all the classes, one fix in the superclass changes the behavior in the subclasses as well.

For programmers coming from C plus plus where multiple inheritance is OK, there is an important difference in Java in the single inheritance. Other programming languages might allow more than one superclass, but this is not allowed in Java.

Once you get used to inheritance and see the true benefits, it can really save so much time.

Published by Cloudage

I am a student studying and tutoring in math, chemistry and physics.  View profile

  • Java's form of inheritance is called single inheritance.
  • Other programming languages allow several superclasses to one subclass.
  • The cruicial terms are superclass and subclass.

To comment, please sign in to your Yahoo! account, or sign up for a new account.