1.

How do you achieve multiple inheritances in Java?

Answer»

The only way to implement multiple inheritances is to implement multiple interfaces in a class. In Java, one class can implement two or more interfaces. As all methods declared in interfaces are implemented in the class, this does not cause any ambiguity.

EXAMPLE:

 // Importing input output classesimport java.io.*; // Class 1// First PARENT classclass PARENT1 { // Method inside first parent class void fun() { // Print statement if this method is CALLED System.out.println("Parent1"); }} // Class 2// Second Parent Classclass Parent2 { // Method inside first parent class void fun() { // Print statement if this method is called System.out.println("Parent2"); }} // Class 3// Trying to be child of both the classesclass Test extends Parent1, Parent2 { // Main driver method public static void main(String args[]) { // Creating OBJECT of class in main() method Test t = new Test(); // When we try to call above functions of class, error is thrown as this class is inheriting multiple classes t.fun(); }}

In the above example, we have defined a method inside both parent classes. When we use “class Test extends Parent1, Parent2”, an error is thrown as this class is inheriting multiple classes.



Discussion

No Comment Found