How is inheritance in Java different from inheritance in the real world?

I got this question in an interview. By inheritance from the real world, the interviewer meant things like off springs inheriting some wealth, some characteristics of the parents, etc.

I have a feeling that this question is something to talk about and does not give a good interview.

Can this question be answered?


source to share

5 answers

Yes, this question can be answered very well and I think this is a good interview question; if you can answer this, it shows that you understand one of the basic concepts of object oriented programming.

Inheritance in object-oriented programming means something completely different than biological inheritance. Inheritance in OO means specialization and implies a relationship : an instance of a subclass is a specialized instance of its superclass.

For example, let's say you have class Cat extends Animal

. A cat is an animal.

Sometimes people use the words "Parent" and "Child" in class inheritance examples where they should have class Parent

and class Child extends Parent

. This is wrong: the child is not a (specialized) parent.



This is a very vague question. The only thing I can remember is that Java inherits only one parent, while Real Life inheritance can have more than one. Possibly, though people use interfaces as a workaround.



In the real world, multiple inheritance is allowed. For example, among animals, children extend the genes of both parents. However, in Java, a child can only have one parent.



In my culture, children inherit their family name (for you java geeks, a genus surname like a package name) from their father (For java geeks, a father is like a special kind of superclass and a mother is another special kind of superclass. Each child has exactly one father and one mother.)

In java, a class can have any package name (within the standard constraints), and there is one superclass and multiple (0, 1 or more superinterfaces).



In Java, Inheritance is a property whereby one class extends or inherits the properties of another class. Therefore, if you take the example of real life inheritance, the son inherits the combination of DNA qualities from his father and mother. So if you are asking for the difference between real life inheritance and Java inheritance, the main difference I find is you cannot inherit multiple inheritance classes in Java whereas in real life multiple inheritance is possible.

In addition, you can also think of Real Life wealth and property inheritance as layered inheritance in Java, where you inherit a superclass property from a subclass and later pass it on to another level.



All Articles