Saturday, September 9, 2023

Top 21 Java Inheritance Interview Questions and Answers

Hello Java and Object-Oriented Programmers, Last week I wrote about some good Java OOP concept questions and In this article, I am going to share some frequently asked Inheritance-based Java Interview questions and answers. Inheritance is one of the most important Object-oriented concepts along with Abstraction, Encapsulation, and Polymorphism. Since most popular languages are object-oriented like Java and C++, you will always find a couple of questions from OOP concepts, particularly from Polymorphism and Inheritance

It's expected from Java developers to know about these OOP concepts and have an understanding of when to use them as many times Composition is the better choice than Inheritance because of flexibility it offers but when it comes to leverage polymorphism of type, you have to use Inheritance. In Java inheritance is supported by language using extends and implements keyword.

In Java, a class can extend another class and implement interface but an interface can only extend other interfaces. At the same time, Java doesn't support multiple inheritances just like C++ does, but it does support multiple inheritances of type by allowing an interface to extend multiple interfaces. You will see many of such Inheritance based Java questions in this article.


BTW, if you are an absolute beginner and wants to learn Object-oriented programming in Java, I suggest to take a look at Head First Object Oriented Analysis and Design, it's fun to read, easy to understand and contains good examples to explain key concepts.




21 Frequently asked Java Inheritance Interview Questions and Answers

Here is my list of some interview questions based upon Inheritance OOP concept asked in various Java interviews. It's very useful for beginners, freshers, and junior Java programmers, but intermediate Java developers can also benefit from some advanced questions shared in this article e.g. position of multiple inheritances in Java after JDK 1.8 release, which allows you to write code inside interface in the form of default methods or explaining Liskov substitution principle.


Question 1: What is Inheritance in Java? (detailed answer)
Answer: Inheritance is an Object oriented feature which allows a class to inherit behavior and data from other class. For example, a class Car can extend basic feature of Vehicle class by using Inheritance. 

One of the most intuitive examples of Inheritance in the real world is Father-Son relationship, where Son inherit Father's property. If you don't know, Inheritance is the quick way to become rich :)


Question 2: What are different types of Inheritance supported by Java? (detailed answer)
Answer: Java supports single Inheritance, multi-level inheritance and at some extent multiple inheritances because Java allows a class to only extend another class, but an interface in Java can extend multiple inheritances.

Types of Inheritance in Java



Question 3: Why multiple Inheritance is not supported by Java? (detailed answer)
Answer: Java is introduced after C++ and Java designer didn't want to take some C++ feature which is confusing and not essential. They think multiple inheritances is one of them which doesn't justify complexity and confusion it introduces. You can also check why multiple inheritances are not supported in Java for more reasons and discussion around this.


Question 4: Why Inheritance is used by Java Programmers? (detailed answer)
Answer: Inheritance is used for code reuse and leveraging Polymorphism by creating a type hierarchy. It's better to use Inheritance for type declaration but for code reuse composition is a better option because it's more flexible. See this article for learning more about why Composition is better than Inheritance.


Question 5: How to use Inheritance in Java? (detailed answer)
Answer: You can use Inheritance in Java by extending classes and implementing interfaces. Java provides two keywords extends and implements to achieve inheritance.  A class which is derived from another class is known as a subclass and an interface which is derived from another interface is called subinterface. A class which implements an interface is known as implementation.



Question 6: What is the syntax of Inheritance? (detailed answer)
Answer: You can use either extends of implements keyword to implement Inheritance in Java.  A class extends another class using extends keyword, an interface can extend another interface using extend keyword, and a class can implement an interface using implements keyword in Java.


Question 7: What is the difference between Inheritance and Encapsulation? (detailed answer)
Answer: Inheritance is an object oriented concept which creates a parent-child relationship. It is one of the ways to reuse the code written for parent class but it also forms the basis of Polymorphism. On the other hand, Encapsulation is an object oriented concept which is used to hide the internal details of a class e.g. HashMap encapsulate how to store elements and how to calculate hash values.


Question 8: What is the difference between Inheritance and Abstraction? (detailed answer)
Answer: Abstraction is an object oriented concept which is used to simply things by abstracting details. It helps in the designing system. On the other hand, Inheritance allows code reuse. You can reuse the functionality you have already coded by using Inheritance. See Head First Object Oriented Analysis and Design for more details.

Java Inheritance Interview Questions Answers



Question 9: What is the difference between Polymorphism and Inheritance? (detailed answer)
Answer: Both Polymorphism and Inheritance goes hand on hand, they help each other to achieve their goal. Polymorphism allows flexibility, you can choose which code to run at runtime by overriding.  See the detailed answer for more details.


Question 10: What is the difference between Composition and Inheritance in OOP? (detailed answer)
Answer: One of the good question to check the candidate's object-oriented programming skills. There are several differences between Composition and Inheritance in Java, some of them are following:

1. The Composition is more flexible because you can change the implementation at runtime by calling setXXX() method, but Inheritance cannot be changed i.e. you cannot ask a class to implement another class at runtime.

2. Composition builds HAS-A relationship while Inheritance builds IS-A relationship e.g. A Room HAS A Fan, but Mango IS-A Fruit.

3. The parent-child relationship is best represented using Inheritance but If you just want to use the services of another class use Composition. For more differences see 5 reasons to favor composition over Inheritance.

Java Inheritance Interview Questions and Answers



11. Can we override static method in Java? (detailed answer)
No, you cannot override a static method in Java because it's resolved at compile time. In order for overriding to work, a method should be virtual and resolved at runtime because objects are only available at runtime. This is one of the tricky Java questions, where interviewer tries to confuse you. A programmer is never sure about whether they can override or overload a static method in Java.


12. Can we overload a static method in Java? (detailed answer)
Yes, you can overload a static method in Java. Overloading has nothing to do with runtime but the signature of each method must be different. In Java, to change the method signature, you must change either number of arguments, type of arguments or order of arguments.


13. Can we override a private method in Java? (detailed answer)
No,  you cannot override a private method in Java because the private method is not inherited by the subclass in Java, which is essential for overriding. In fact, a private method is not visible to anyone outside the class and, more importantly, a call to the private method is resolved at compile time by using Type information as opposed to runtime by using the actual object.


Question 14: What is method hiding in Java? (detailed answer)
Answer: Since the static method cannot be overridden in Java, but if you declare the same static method in subclass then that would hide the method from the superclass. It means, if you call that method from subclass then the one in the subclass will be invoked but if you call the same method from superclass then the one in superclass will be invoked. This is known as method hiding in Java.


Question 15: Can a class implement more than one interface in Java? (detailed answer)
Yes, A class can implement more than one interface in Java e.g. A class can be both Comparable and Serializable at the same time. This is why the interface should be the best use for defining Type as described in Effective Java. This feature allows one class to play a polymorphic role in the program.


Question 16: Can a class extends more than one class in Java? (detailed answer)
Answer: No, a class can only extend just one more class in Java.  Though Every class also, by default extend the java.lang.Object class in Java.


Question 17: Can an interface extends more than one interface in Java? (answer)
Answer: Yes, unlike classes, an interface can extend more than one interface in Java. There are several example of this behavior in JDK itself e.g. java.util.List interface extends both Collection and Iterable interface to tell that it is a Collection as well as it allows iteration via Iterator.


18: What will happen if a class extends two interfaces and they both have a method with same name and signature? (detailed answer)
In this case, a conflict will arise because the compiler will not able to link a method call due to ambiguity. You will get a compile time error in Java.


Question 19: Can we pass an object of a subclass to a method expecting an object of the super class? (answer)
Answer: Yes, you can pass that because subclass and superclass are related to each other by Inheritance which provides IS-A property.  I mean Banana is a Fruit so you can pass banana if somebody expect fruit. Now there are scenario, where you can't do e.g. when subclass violates the Liskov Substitution principle i.e. you cannot pass a plastic banana to someone expecting fruit :-), The eat() function will throw exception.

Liskov Substitution Principle in Java


Question 20: What is the Liskov substitution principle? (detailed answer)
Answer: The Liskov substitution principle is one of the five object-oriented design principles, collectively know as SOLID principles

This design principle is L of SOLID acronym. The Liskov substitution principle states that in an object oriented program if a function or method is expecting an object of base class then  it should work fine with a derived class object as well. If it cannot function properly with derived class object then the derived class is violating the Liskov Substitution principle.

For example, if a method is expecting a List you can also pass ArrayList or LinkedList and it should work just fine because ArrayList and LinkedList both follow Liskov Substitution Principle, but the java.sql.Date which is a subclass of java.util.Date in Java violates Liskov Substitution Principle because you cannot pass an object of java.sql.Date class to a method which is expecting an object of java.util.Date, Why? because all time-related method will throw java.lang.UnsupportedOperationException.

Here is another example of violating The Liskov Substitution Principle, Square is a special type of Rectangle whose adjacent sides are equal but making Square extending Rectangle violates LSP principle. For more details on SOLID design principles, read Clean Code by Rober C. Martin, the inventor of SOLID principles.

Inheritance Object Oriented Programming Questions




Question 21: How to call a method of a subclass, if you are holding an object of the subclass in a reference variable of type superclass? (answer)
Answer: You can call a method of the subclass by first casting the object hold by reference variable of  superclass into the subclass. Once you hold the object in subclass reference type, you can call methods from the subclass. See how type casting works in Java for more details.


That's all about some good interview questions based OOP concept,  Inheritance. You should also know that how private and final variables affect Inheritance. How can you extend a class which is holding a private variable, and probably the difference between private and protected modifier in Java? They are really important to understand and use Inheritance in Java.

Also, if you think we have missed any important question related to Inheritance o If you come across any good questions based upon Inheritance or other object-oriented concept then please share with us.

Related Interview Questions from Java67 blog

Thanks for reading this article so far. If you like these Java  Inheritance interview questions or have seen them on your telephonic round of interview, then please share this post with your friends and colleagues on Facebook, Twitter, Email, etc. If you have any questions or feedback, please drop a note.

17 comments:

  1. Very helpfull guide for beginners.... carry on i think this is the best tutorial

    ReplyDelete
  2. Q18 Answer is wrong.. In case of same signature method no compiler error. But in case of variable that kind ambiguous problem will arise.

    ReplyDelete
  3. Q18 answer is wrong. In case of same signature method in multiple interface there is no compiler error..
    But in case of same variable in multiple interfaces this kind ambiguous problem will arise.

    ReplyDelete
  4. Excellent questions!appreciate it if it is based on more technical questions rather than basic definitions.

    ReplyDelete
  5. Replies
    1. yup, it has typo.

      Instead of "you cannot overload a static method in Java", you should read you can.

      Static method cannot be overridden but can be overloaded. remember, overloading happens in same class while overriding happens at subclass.

      Delete
  6. 18: What will happen if a class extends two interfaces and they both have a method with same name and signature? (detailed answer)

    THe answer of this question is wrong

    ReplyDelete
  7. in Q.18 i think there is error because we can implements more than one interface and i think there will not any error if they both have have signature method.

    ReplyDelete
  8. 18: What will happen if a class extends two interfaces and they both have a method with same name and signature? (detailed answer)

    THe answer of this question is wrong.
    Answer :
    Code will compile properly and there is no ambigutiy as only one method implementation will be there,Compiler does not have to distinguish the method from which Interface it is

    ReplyDelete
  9. Yes, it is wrong because if you have same name and signature then only one implementation is provided to the public abstract method in both the interfaces which the class implement them, if not declare the class abstract

    ReplyDelete
  10. Question no 18
    Program compile successfully because multiple inheritance is supported in Java through interface

    ReplyDelete
  11. very helpful tese question and answer.

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.