Java multiple inheritance

shown by example:

We need multiple inheritance when developing the Web client that talks to the message server. Our Web client is a simple servlet used to get the message from a form and send it to the message server. To complete that task, the servlet must be both an HttpServlet and a MessageClient. Since Java does not allow such behavior, the main class extends the HttpServlet class, as shown in Listing 2. This main class contains an inner class that extends MessageClient. The outer class then creates an instance of the inner class.

public class SendMessageServlet extends HttpServlet{

private MessageClient m_messageClient;
private String m_serverName;

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
//Get server name
m_serverName = request.getServerName();
System.out.println("ServerName is " + m_serverName);
//Create message client to communicate with message server
m_messageClient = new ServletMessageClient();
System.out.println("Created Message Client");

//Get message and phone number
String phoneNum = (String) request.getParameter("PhoneNum");
String message = (String) request.getParameter("Message");

//Send message

//Display page to tell user message was sent
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/SendMessageForm.jsp");
dispatcher.include(request, response);
}catch (Exception e){

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);

/** Inner class used to extend MessageClient */
public class ServletMessageClient extends MessageClient {
public ServletMessageClient(){
public String getServerName(){
System.out.println("Returning ServerName " + m_serverName);

This approach isn’t true multiple inheritance because we used delegation. (i.e., MessageClient is extended by a member of the outer class and not the outer class itself), but the effect is the same. Although MessageClient could have been extended in a separate class, using an inner class allows it to access all the members and methods of the outer class. This makes it easier for the two classes to interact.

This example only extends two classes, but there is no reason why this technique couldn’t be used to extend as many classes as needed by creating an inner class for each class that must be inherited.


Leave a Reply

Your email address will not be published. Required fields are marked *

Please reload

Please Wait