×

Multiple Inheritance Programs in Java

A component of the object-oriented notion known as multiple inheritances allows a class to inherit properties from multiple parent classes. When methods that have the same signature are present in both superclasses and subclasses, an issue arises. The method's caller cannot specify to the compiler which class method should be called or even which class method should be given precedence.

NOTE: Multiple Inheritances is not supported by Java.

Example 1:

import java.io.*;
class Parent1 {
void fun() {
	System.out.println("Parent1");
}
}
class Parent2 {
void fun() {
	System.out.println("Parent2");
}
}
class Test extends Parent1,Parent2 {
public static void main(String args[]) {
	Test t = new Test();
	t.fun();
}
}

Output

C:\javap>java Demo.java
Demo.java:12: error: '{' expected
class Test extends Parent1,Parent2 {
                          ^
1 error

Conclusion: As shown in the code above, issues can arise when utilizing the Test object to call the fun() function, such as deciding whether to use Parent1's or Parent2's fun() method.

Example 2:

import java.io.*;
class GrandParent {
void fun() {
	System.out.println("Grandparent");
}
}
class Parent1 extends GrandParent {
void fun() {
	System.out.println("Parent1");
}
}
class Parent2 extends GrandParent {
void fun() {
	System.out.println("Parent2");
}
}
class Test extends Parent1, Parent2 {
public static void main(String args[]) {
	Test t = new Test();
	t.fun();
}
}

Output

C:\javap>javac Demo.java
Demo.java:17: error: '{' expected
class Test extends Parent1, Parent2 {
                          ^
1 error

The fun() method throws a compiler error once more because multiple inheritances, which are permitted in other languages like C++, lead to a diamond problem. The code reveals the following: Problems arise when the method fun() is called using the Test object, such as when deciding whether to call the fun() method of Parent1 or Parent2. Java consequently does not allow multiple class inheritances in order to prevent these issues.

Java classes do not enable multiple inheritances, and managing the complexity brought on by multiple inheritances is exceedingly difficult. It causes issues with a number of processes, such as casting and function Object() { [native code] } chaining, and the main reason is that multiple inheritancesare rarely necessary; therefore, it is preferable to do without it to make things clear-cut and simple.

How do Default Methods & Interfaces Solve the Aforementioned Issues?

Java 8 allows interfaces to give a default implementation of methods, and Java 8 supports this. Additionally, a class may support two or more interfaces. If the default methods in both implemented interfaces have the same method signature, the implementing class must either use the super keyword to explicitly specify which default method is to be used in a method other than main(), override the default method in the implementing class, or specify which standard method is to be used in the default overridden method of the effective implementation class.

Example 3:

interface P1{
	default void show()
	{
		System.out.println("Default P1");
	}
}
interface P2 {
	default void show()
	{
		System.out.println("Default P2");
	}
}
class TestClass implements P1, P2 {
	public void show()
	{
		P1.super.show();
		P2.super.show();
	}
	public void showOfP1() {
		P1.super.show();
	}
	public void showOfP2() {
		P2.super.show(); 
	}
	public static void main(String args[])
	{
		TestClass d = new TestClass();
		d.show();
		System.out.println("Now Executing showOfP1() showOfP2()");
		d.showOfP1();
		d.showOfP2();
	}
}

Output

interface P1{
	default void show()
	{
		System.out.println("Default P1");
	}
}
interface P2 {
	default void show()
	{
		System.out.println("Default P2");
	}
}
class TestClass implements P1, P2 {
	public void show()
	{
		P1.super.show();
		P2.super.show();
	}
	public void showOfP1() {
		P1.super.show();
	}
	public void showOfP2() {
		P2.super.show(); 
	}
	public static void main(String args[])
	{
		TestClass d = new TestClass();
		d.show();
		System.out.println("Now Executing showOfP1() showOfP2()");
		d.showOfP1();
		d.showOfP2();
	}
}

NOTE: There is a compiler issue if the default method implementation is removed from "TestClass". There won't be a problem if none of the intermediary interfaces implement the root interface if there is a diamond through an interface. If they offer implementation, it can be obtained via the super keyword as described above.

Example 4:

interface GP1 {
	default void show()
	{
		System.out.println("Default GP1");
	}
}
interface P1 extends GP1 {
}
interface P2 extends GP1{
}
class TestClass implements P1, P2 {
	public static void main(String args[])
	{
		TestClass d = new TestClass();
		d.show();
	}
}

Output

Default Gp1

Example 5:

interface Backend {
  public void connectServer();
}


class Frontend {
  public void responsive(String str) {
System.out.println(str + " is utilized as a front-end language.");
  }
}
class Language extends Frontend implements Backend {


  String language = "Java";
  public void connectServer() {
System.out.println(language + " is utilized as the backend language.");
  }


  public static void main(String[] args) {
    Language java = new Language();
java.connectServer();
java.responsive(java.language);
  }


}

Output

java is utilized as the backend language.
Java is utilized as a front-end language.

Related Topics

Trim Method in String Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

3 minutes read.

Compile-time Error in Java

In java, the execution of a program is stopped due to the occurrence of some problem known as an error. Errors are illegal operations that are carried out by the...

4 minutes read.

Java Comparable Interface

We implement comparable interface when we need a new logic for determining equality. if two objects are equal, the equals() method returns true and compareTo() method returns 0. The basic...

1 minute read.

What is Core Java?

The fundamental Java, which includes the fundamental idea of the Java programming language, is referred to as "Core Java." The definition of "Core" is the core idea of something. Core...

3 minutes read.

Java Architecture

Java architecture is a combination of three parts they are JVM, JRE and JDK. These components will help in the functioning of the java programs. The process of code interpretation...

6 minutes read.

Java Boolean hashCode() Method

The hashCode() method of Boolean class returns the hash code for the specified Boolean object or the given Boolean value. Syntax public int hashCode()public int hashCode(boolean value) Parameters The parameter ‘value’ represents the value...

2 minutes read.

How to generate random numbers in Java

Random numbers, also known as fake numbers, are actually a part of a very large sequence, so they are called random numbers. In a defined set of numbers, every number...

6 minutes read.

Java Arrays

An array is an object that stores a collection of values. An array can store two types of collection data: objects and primitives. An array is a collection of values which...

2 minutes read.

Java Get Time in UTC

UTC is the abbreviation for Universal Time Coordinated. Before the beginning of UTC, it is mentioned as the Greenwich Mean Time (GMT) but Now it is mentioned as the universal...

4 minutes read.

Java Extends vs Implements

Java: We known that the java is a pure object oriented programming language. Java programming language consists of many features such as portable, plat form independence, secured, robust, simple, architecture neutral,...

4 minutes read.

Java Return Keyword

The return keyword in Java is used to end a method's execution. the caller receives the return, followed by the appropriate value. The return type of the method, such as...

3 minutes read.

Java Math sin() Method

The sin() method of Java Math class returns the trigonometric sine of the specified angle. Syntax: public static double sin(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The sin() method...

1 minute read.

Java String startsWith() method

Java String startsWith() method checks whether current String starts with given prefix or not . Syntax: public boolean startsWith(String prefix) public boolean startsWith(String prefix, int offset) Parameters: prefix : It is sequence of character Returns: It returns...

2 minutes read.

flour pack problem in Java

Create a method called canPack and give it three int parameters: bigCount, smallCount, and objective. The bigCount option indicates the number of large flour bags (5 kilos each). The smallCount argument indicates...

3 minutes read.

Alice and Bob Problem Java

Alice and Bob were two friends who liked to play games. Both together found a game, which has the description below. The game begins with an integer num, used to create...

2 minutes read.

GCD of Different SubSequences in Java

The positive numbers are provided in an array called inArr. The aim is to determine the number of distinct GCDs (Greatest Common Divisors) in each subsequence present in the input...

4 minutes read.

How to Convert String to double in Java

How to Convert String to double in java It is used if we have to perform mathematical operations on the string that contains a double number. When we get data from...

3 minutes read.

How to download and install Eclipse in Windows?

Download and Install Eclipse on Windows Eclipse is an open source IDE (Integrated Development Environment) which is used to help the programmers to provide a platform to write and run the...

1 minute read.

How to increment and decrement date using Java?

Before understanding how to increment and decrement the date, one must know about the Calendar class in Java. The Java calendar class offers methods for converting dates between a given moment...

3 minutes read.

Volatile keyword in Java

Multiple threads can change a variable's value by using the volatile keyword. Making classes thread-safe is another application for it. It indicates that using a method or an instance of...

3 minutes read.