Java training institutes in Kukatpally

What Is Java Inheritance?

Inheritance in Object Oriented Programming is one of the main principles. It can be used in the design of almost any application. Java inheritance allows a way to identify the interaction between objects. It also helps in re-use of code. So that to make sure you are not using same code continuously. It provides code re-usability. So we need not write the code again but can re-use it.

Java Inheritance

So what I mean when I say that inheritance allows you to define the relationship among objects? Well, this allows us to think of some examples of Objects that have one or more relationships. Take for example object Vehicle, this is a common term for:

  1. Motorcycle
  2. Car
  3. Bus

Now here you can see Car is a vehicle, Bus is a vehicle, Motorcycle is a vehicle etc. This "is a" relationship is what Java Inheritance is all about. When you say something "is a" something else. Then you really have a relationship between those two Objects, therefore you have Inheritance.

How does Inheritance help us?

Well, considering cases given above, it means that Car inherits behavior or attributes from a Vehicle. So let us think about this, what exactly a Car is? Well, it's a Vehicle with four wheels, doors, and five seats. Now, what is a Bus? It is also a Vehicle exceeding four wheels, doors and approximately 30 seats available. What is a Motorcycle? It's really a Vehicle with two wheels, no doors, and one or two seats. At the time you begin to figure out every one of the characteristics of Objects. You shall start to observe just similarities they may have. In addition what they do not have in relation to other. This is very important with Java inheritance. Whenever Objects share something in common. Then this can be considered an attribute of the superclass. Whatever they do not share will be attributes of child classes.

What is a super Class and what is a child Class?

With this example, the superclass is object Vehicle and child classes are Car, Bus and Motorcycle. The super Class is Object that will maintain each of the properties which are common. Therefore our Vehicle super Class will have the following components:

  • Wheels
  • Seats

Due to our observation of all the varieties of Vehicles above, we note that all types of Vehicles have wheels and seats. But, notice that I did not put doors as part of the Vehicle object. The reason is Motorcycles do not have doors. Doors would be attributes of Cars and Buses, so we will have a door attribute in Car and Bus Objects.