InterviewSolution
| 1. |
Does Java allow a class to inherit from multiple classes? If not, how can a class achieve the properties of more than one class (i.e., multiple inheritance)? |
|
Answer» Multiple inheritances are not allowed by Java using classes. This is because dealing with the complexity that multiple inheritances PRODUCE is quite difficult. For example, import java.io.*;class Base1 { void fun() { System.out.println("Parent1"); }} class Base2 { void fun() { System.out.println("Parent2"); }} class Child extends Base1, Base2 { public static void main(String ARGS[]) { Child obj = new Child(); // object creation of the child class obj.fun(); // it leads to compilation error since fun() is defined in both Base1 and Base2 and the compiler gets in an ambiguous situation as to which fun() is being referred to. }}In the above code, a compilation error is thrown. This is because both the classes Base1 and Base2 contain a definition for the function fun(). This confuses the compiler as to which fun() is being referred to. Multiple Inheritance causes issues during operations such as casting, constructor chaining, and so on, and the main reason is that we only NEED multiple inheritances in a few cases, thus it's best to leave it out to keep things simple and easy. However, the main objective of multiple inheritances to inherit from multiple classes can be obtained via interfaces in Java. An interface, LIKE a class, has variables and methods, however, unlike a class, the methods in an interface are abstract by default. The class that implements an interface needs to define the member functions. If a class implements multiple interfaces, or if an interface extends multiple interfaces, multiple inheritances via interface happen. For example, the code for the above example using interfaces would be like this: interface Base1{ public void fun();}interface Base2{ public void fun();}class Child implements Interface1, Interface2{ public void fun() { System.out.println("Implementing the fun() of the interface."); } public static void main(String args[]){ Child obj = new Child(); obj.fun(); }}In the above code, the fun() is not defined in the interfaces Base1 and Base2. They are defined by the classes which implement the interfaces. This leads to no ambiguity and the purpose of multiple inheritances has been solved. |
|