Inheritance Java Interview Questions – Set 02

How can we implement polymorphism in Java ?

Polymorphism is the capability of an action or method to do different things based on the object that it is acting upon.

There are two types of polymorphism:-

  • Method Polymorphism through overloading.
  • Object polymorphism by inheritance / interfaces.

What are the advantages of the model over the event-inheritance model

The event-delegation model has two advantages over the event-inheritance model. They are: a)It enables event handling by objects other than the ones that generate the events. This allows a clean separation between a component’s design and its use. b)It performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to be repeatedly process unhandled events as is the case of the event-inheritance.

Which one would you prefer and why

The Runnable interface is preferred, as it does not require your object to inherit a thread because when you need multiple inheritance, only interfaces can help you. In the above example we had to extend the Base class so implementing Runnable interface is an obvious choice.

Also note how the threads are started in each of the different cases as shown inthe code sample. In an OO approach you should only extend a class when you want to make it different from it’s superclass, and change it’s behavior.

By implementing a Runnable interface instead of extending the Thread class, you are telling to the user that the class Counter is an object of type Base and will run as a thread.

Explain different way of using thread

A Java thread could be implemented by using Runnable interface or by extending the Thread class. The Runnable is more advantageous, when you are going for multiple inheritance.

Why do we need run() & start() method both. Can we achieve it with only run method

We need run() & start() method both because JVM needs to create a separate thread which can not be differentiated from a normal method call. So this job is done by start method native implementation which has to be explicitly called. Another advantage of having these two methods is we can have any object run as a thread if it implements Runnable interface. This is to avoid Java’s multiple inheritance problems which will make it difficult to inherit another class with Thread.