What is inheritance?

Md Shakib Uddin Bhuiyan
2 min readNov 6, 2020
Photo by Марьян Блан | @marjanblan on Unsplash

Let’s explain with an example from the Marvel Cinematic universe. If you are a marvel fan, you must have come across The Avengers and their leader Tony Stark known as The Iron Man. In the latest Avengers movie, Tony Stark died defending the earth from the mad titan Thanos. After his death, who would get access to all his wealth and Powerful battle suits? His daughter Morgan, right?

Morgan, The next Iron Man, will inherit all of Tony’s resources, including the battle suits.

Inheritance is something that is inherited from someone.

In Object-Oriented Programming, Inheritance can be defined as the process where one class (Subclass) acquires the properties (methods and fields) of the class(Superclass) it’s inheriting from.

See the codes below.

If you look at the code snippet above you will see that there are two classes TonyStrak in a package named marvel.phase3 and MorganStark in a package named marvel.phase4.

In TonyStark class tony’s suits are initialized using a public constructor. The class MorganStark inherits TonyStark with the extends keyword at line 7. After that MorganStark accessed all of the suits from TonyStark class, by calling the getRegularSuits and getSpecialSuits protected methods.

This is called inheritance.

So, here TonyStark is the superclass and MorganStark is the subclass. When you run the MorganStark class this line will be printed on the output screen.

Morgan Stark’s inherited suits are: [Mark 1, Mark 2, Hulk Buster, Thor Buster]

Photo by Sam Balye on Unsplash

Now Let’s add another class in marvel.phase4.

At the end of Avengers Tony left something special for peter.

EDITH !, An augmented reality security, defence, and artificial tactical intelligence system.

PeterParker class inherits TonyStark class the same way using the extends keyword. So, PeterParker gets access to EDITH using the getGiftForSpiderMan protected method.

Peter had to put a security code in the super() method as a parameter at line 7. Because of that, the parameterized constructor of TonyStark was called. The super keyword is used to access the superclass constructor.

When you run the PeterParker class these lines will be printed on the output screen.

Hello Peter

Peter Parker inherited: EDITH

Now try putting something different as security code in the super method in PeterParker class. For example, try putting “Quentin Beck” and tell me what happens.

Get full code at this link.

Give a Star if you like my projects in GitHub.

Thanks for reading.

--

--