How would you implement multiple    inheritance in Java?    Multiple inheritance is the ability to inherit from multiple c...
Note: For a discussion of the diamond problem, a classic multiple inheritance challenge,read Bill Vennerss "Designing with...
IntroductionJava was designed without multiple inheritance. While some developers think of this as aflaw, it is actually t...
Here we will suppose that the compatible mixins require that the other class provides amethod getValue that returns an int...
23       {24       public:25       // i want to overide the b function of ChildCol1 only !!26       void b() { cout <&l...
Upcoming SlideShare
Loading in …5
×

How would you implement multiple inheritance in java

8,560 views

Published on

Published in: Technology, News & Politics
1 Comment
0 Likes
Statistics
Notes
  • This page is a good reference:

    http://www.programmerinterview.com/index.php/java-questions/multiple-inheritance/
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Be the first to like this

No Downloads
Views
Total views
8,560
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
58
Comments
1
Likes
0
Embeds 0
No embeds

No notes for slide

How would you implement multiple inheritance in java

  1. 1. How would you implement multiple inheritance in Java? Multiple inheritance is the ability to inherit from multiple classes. Java does not have this capability. However, C++ does support multiple inheritance. Syntactically, multiple inheritance in C++ would look like this, where class X derives from 3 classes – A, B, and C: class X : public A, private B, public C { /* ... */ }; Why doesnt the Java language support multiple inheritance? Whenever you find yourself asking why Java has or does not have some feature, consider the design goals behind the Java language. With that in mind, I started my search by skimming through "The Java Language Environment" by James Gosling and Henry McGilton (Sun Microsystems), a white paper published in May 1996 that explains some of the reasoning behind Javas design. As the white paper states, the Java design team strove to make Java:• Simple, object oriented, and familiar• Robust and secure• Architecture neutral and portable• High performance• Interpreted, threaded, and dynamic The reasons for omitting multiple inheritance from the Java language mostly stem from the "simple, object oriented, and familiar" goal. As a simple language, Javas creators wanted a language that most developers could grasp without extensive training. To that end, they worked to make the language as similar to C++ as possible (familiar) without carrying over C++s unnecessary complexity (simple). In the designers opinion, multiple inheritance causes more problems and confusion than it solves. So they cut multiple inheritance from the language (just as they cut operator overloading). The designers extensive C++ experience taught them that multiple inheritance just wasnt worth the headache.
  2. 2. Note: For a discussion of the diamond problem, a classic multiple inheritance challenge,read Bill Vennerss "Designing with Interfaces" (JavaWorld, December 1998) and TonySintess "Java Diamonds Are Forever" (JavaWorld, March 2001).Instead, Javas designers chose to allow multiple interface inheritance through the use ofinterfaces, an idea borrowed from Objective Cs protocols. Multiple interface inheritanceallows an object to inherit many different method signatures with the caveat that theinheriting object must implement those inherited methods.Multiple interface inheritance still allows an object to inherit methods and to behavepolymorphically on those methods. The inheriting object just doesnt get an implementationfree ride. For an excellent discussion of interface inheritance, read Wm. Paul Rogerss"Reveal the Magic Behind Subtype Polymorphism When Sun was designing Java, it omitted multiple inheritance - or more precisely multiple implementation inheritance - on purpose. Yet multiple inheritance can be useful, particularly when the potential ancestors of a class have orthogonal concerns. This article presents a utility class that not only allows multiple inheritance to be simulated, but also has other far-reaching applications. Have you ever found yourself wanting to write something similar to: public class Employee extends Person, Employment { // detail omitted } Here, Person is a concrete class that represents a person, while Employment is another concreteclass that represents the details of a person who is employed. If you could only put them together,you would have everything necessary to define and implement an Employee class. Except in Java- you cant. Inheriting implementation from more than one superclass - multiple implementationinheritance - is not a feature of the language. Java allows a class to have a single superclass and no more. On the other hand, a class can implement multiple interfaces. In other words, Java supports multiple interface inheritance. Suppose the PersonLike interface is: public interface PersonLike { String getName(); int getAge(); } and the EmployeeLike interface is: public interface EmployeeLike { float getSalary(); java.util.Date getHireDate(); }
  3. 3. IntroductionJava was designed without multiple inheritance. While some developers think of this as aflaw, it is actually true that the overall design of Java supports the solution of problemscommonly solved with multiple inheritance in other ways. In particular, the singly rootedhierarchy (with Object as the ultimate ancestor of all classes) and Java interfaces solvesmost problems that are commonly solved using multiple inheritance in C++.However, there are a few situations in which multiple inheritance is very helpful. In thisnote we will consider one special case and also the general case of multiple inheritance.Mixin InheritanceIn mixin inheritance, one class is specifically designed to be used as one of the classes ina multiple inheritance scheme. We say that it provides some functionality that is "mixedin" to some other class that wants this functionality. Another way to think of mixininheritance is that a mixin class is given a new parent class so that the mixin seems toextend the other class. In some projects it is necessary to rely on common services thatmust be provided by several classes. Mixin inheritance is one way to centralize thedevelopment of these services.To provide for mixin inheritance we will need to define two interfaces as well a at leastone class that provides the service: the Mixin class. In some situations, one of theseinterfaces is empty and may then be omitted.The InterfacesThe first interface (always required) defines what the mixin class will provide forservices. It defines one or more methods that will be implemented by the mixin class. Wewill take a simple and abstract example here. The class will be called (abstractly)MProvides to emphasize that it defines what any compatible mixin must provide. We willalso assume that the only service provided is a void function and we will give it theabstract name func. In practice, however, there may be any number of methods definedand they may have any signatures.interface MProvides{ void func();}One special feature of mixin inheritance that is not usually present in the general multipleinheritance case is that the mixin class may require services of the class into which it ismixed. That is, in order to provide the "func" service, the mixin may need to get someinformation from the other class. We define this with another interface. We will give itthe abstract name MRequires to indicate that it requires one or more services from theclass into which it is mixed.
  4. 4. Here we will suppose that the compatible mixins require that the other class provides amethod getValue that returns an int.interface MRequires{ int getValue();}Why multiple inheritance is not allowedin Java?For long time I had a question “why Sun introduced Interface concept instead of C++ style of multipleinheritance?“. I did googling but many articles and forums talks about difference between abstract classand Interface not why Interface concept required in Java. After extensive search and analysis I came toknow the reason behind the Interface concept in Java.In C++ multiple inheritance is possible, virtual keyword is been used to define virtual function. Whereas inJava multiple inheritance is not possible however using Interface concept the same class can representdifferent structure.Lets take an example in C++ where two parent class contains same virtual function.Example: 1 class BaseCol2 {3 public:4 virtual void a() { cout << "BaseCol::a" << endl; }5 virtual void b() { cout << "BaseCol::b" < endl; }6 };78 class ChildCol1 : public BaseCol9 {10 public:11 virtual void a() { cout << "ChildCol1::a" << endl; }12 virtual void b() { cout << "ChildCol1::b" << endl; }13 };1415 class ChildCol2 : public BaseCol16 {17 public:18 virtual void a() { cout << "ChildCol2::a" << endl; }19 virtual void b() { cout << "ChildCol2::b" << endl; }20 };2122 class Row : public ChildCol1, public ChildCol2
  5. 5. 23 {24 public:25 // i want to overide the b function of ChildCol1 only !!26 void b() { cout << "Row1::b" << endl; }27 };While executing the above code at runtime ambiguity error will occur since the implementation hasconflicting methods. This problem is called Diamond inheritance problem.To avoid this complexity Java provides single inheritance with interface concept. Since interface cannothave method implementation, the problem is therefore avoided since there is always only oneimplementation to a specific method and hence no ambiguity will arise.

×