Java Multiple Inheritance Last Updated : 26 Dec, 2024 Comments Improve Suggest changes Like Article Like Report Multiple Inheritance is a feature of an object-oriented concept, where a class can inherit properties of more than one parent class. The problem occurs when there exist methods with the same signature in both the superclasses and subclass. On calling the method, the compiler cannot determine which class method to be called and even on calling which class method gets the priority. Note: Java doesn't support Multiple InheritanceExample 1: Java // Java Doesn't support Multiple Inheritance import java.io.*; // First Parent Class class Parent1 { void fun() { System.out.println("Parent1"); } } // Second Parent Class class Parent2 { void fun() { System.out.println("Parent2"); } } // Inheriting Properties of // Parent1 and Parent2 class Test extends Parent1, Parent2 { // main method public static void main(String args[]) { // Creating instance of Test Test t = new Test(); t.fun(); } } Output: Compilation error is thrownConclusion: As depicted from code above, on calling the method fun() using Test object will cause complications such as whether to call Parent1’s fun() or Parent2’s fun() method. Example 2: Java Diamond Problem Similar Scenario GrandParent / \ / \ Parent1 Parent2 \ / \ / Test Java // Java Diamond Problem Similar Scenario import java.io.*; // GrandParent Class class GrandParent { void fun() { System.out.println("Grandparent"); } } // Inheriting GrandParent class Parent1 extends GrandParent { void fun() { System.out.println("Parent1"); } } // Inheriting GrandParent class Parent2 extends GrandParent { void fun() { System.out.println("Parent2"); } } // Child Class inheriting Parent1 and Parent2 class Child extends Parent1, Parent2 { // main method public static void main(String args[]) { Child t = new Child(); t.fun(); } } Output: When you run the fun() method in the Test class, it throws a compiler error due to multiple inheritance, which causes the diamond problem (common in languages like C++). In this case, the code doesn't know whether to call Parent1's or Parent2's fun() method, leading to ambiguity. To avoid such complications, Java does not support multiple inheritance with classes.Java avoids multiple inheritance with classes because it can lead to complex issues, such as problems with casting, constructor chaining, and other operations. Moreover, multiple inheritance is rarely needed, so Java excludes it to maintain simplicity and clarity in code.Using Default Methods and Interfaces for Multiple InheritanceJava 8 supports default methods where interfaces can provide a default implementation of methods. And a class can implement two or more interfaces. In case both the implemented interfaces contain default methods with the same method signature, the implementing class should explicitly specify which default method is to be used in some method excluding the main() of implementing class using super keyword, or it should override the default method in the implementing class, or it should specify which default method is to be used in the default overridden method of the implementing class.Example 1: Demonstrating Multiple Inheritance through default methods Java // Interface 1 interface PI1 { default void show(){ System.out.println("Default PI1"); } } // Interface 2 interface PI2 { default void show(){ System.out.println("Default PI2"); } } class TestClass implements PI1, PI2 { // Overriding default show method @Override public void show(){ PI1.super.show(); PI2.super.show(); } // Declared new Method public void showOfPI1() { PI1.super.show(); } // Declared new Method public void showOfPI2() { PI2.super.show(); } // main Method public static void main(String args[]) { // Instance of Class TestClass d = new TestClass(); // Using show Method d.show(); // Executing the Methods System.out.println("Now Executing showOfPI1()" + " showOfPI2()"); d.showOfPI1(); d.showOfPI2(); } } OutputDefault PI1 Default PI2 Now Executing showOfPI1() showOfPI2() Default PI1 Default PI2Note: If we remove the implementation of default method from "TestClass", we get a compiler error. If there is a diamond through interfaces, then there is no issue if none of the middle interfaces provide implementation of root interface. If they provide implementation, then implementation can be accessed as above using super keyword.Example 2: Java // Java program to demonstrate How Diamond Problem // Is Handled in case of Default Methods // Interface 1 interface GPI { // Default method default void show() { // Print statement System.out.println("Default GPI"); } } // Interface 2 // Extending the above interface interface PI1 extends GPI { } // Interface 3 // Extending the above interface interface PI2 extends GPI { } // Main class // Implementation class code class TestClass implements PI1, PI2 { // Main driver method public static void main(String args[]) { // Creating object of this class // in main() method TestClass d = new TestClass(); // Now calling the function defined in interface 1 // from whom Interface 2and 3 are deriving d.show(); } } OutputDefault GPI Comment More infoAdvertise with us Next Article Comparison of Inheritance in C++ and Java kartik Follow Improve Article Tags : Java Computer Science Fundamentals java-inheritance Practice Tags : Java Similar Reads Basics of JavaLearn Java - A Beginners Guide for 2024If you are new to the world of coding and want to start your coding journey with Java, then this learn Java a beginners guide gives you a complete overview of how to start Java programming. Java is among the most popular and widely used programming languages and platforms. A platform is an environme10 min readIntroduction to JavaJava is a high-level, object-oriented programming language developed by Sun Microsystems in 1995. It is platform-independent, which means we can write code once and run it anywhere using the Java Virtual Machine (JVM). Java is mostly used for building desktop applications, web applications, Android4 min readSimilarities and Difference between Java and C++Nowadays Java and C++ programming languages are vastly used in competitive coding. Due to some awesome features, these two programming languages are widely used in industries as well as competitive programming. C++ is a widely popular language among coders for its efficiency, high speed, and dynamic6 min readSetting up Environment Variables For Java - Complete Guide to Set JAVA_HOMEIn the journey to learning the Java programming language, setting up environment variables for Java is essential because it helps the system locate the Java tools needed to run the Java programs. Now, this guide on how to setting up environment variables for Java is a one-place solution for Mac, Win6 min readJava SyntaxJava is an object-oriented programming language that is known for its simplicity, portability, and robustness. The syntax of Java programming language is very closely aligned with C and C++, which makes it easier to understand. Java Syntax refers to a set of rules that define how Java programs are w6 min readJava Hello World ProgramJava is one of the most popular and widely used programming languages and platforms. In this article, we will learn how to write a simple Java Program. This article will guide you on how to write, compile, and run your first Java program. With the help of Java, we can develop web and mobile applicat6 min readDifferences Between JDK, JRE and JVMUnderstanding the difference between JDK, JRE, and JVM plays a very important role in understanding how Java works and how each component contributes to the development and execution of Java applications. The main difference between JDK, JRE, and JVM is:JDK: Java Development Kit is a software develo3 min readHow JVM Works - JVM ArchitectureJVM (Java Virtual Machine) runs Java applications as a run-time engine. JVM is the one that calls the main method present in a Java code. JVM is a part of JRE (Java Runtime Environment). Java applications are called WORA (Write Once Run Anywhere). This means a programmer can develop Java code on one7 min readJava IdentifiersAn identifier in Java is the name given to Variables, Classes, Methods, Packages, Interfaces, etc. These are the unique names used to identify programming elements. Every Java Variable must be identified with a unique name.Example:public class Test{ public static void main(String[] args) { int a = 22 min readVariables & DataTypes in JavaJava VariablesIn Java, variables are containers that store data in memory. Understanding variables plays a very important role as it defines how data is stored, accessed, and manipulated.Key Components of Variables in Java:A variable in Java has three components, which are listed below:Data Type: Defines the kind8 min readScope of Variables in JavaThe scope of variables is the part of the program where the variable is accessible. Like C/C++, in Java, all identifiers are lexically (or statically) scoped, i.e., scope of a variable can be determined at compile time and independent of the function call stack. In this article, we will learn about7 min readJava Data TypesJava is statically typed and also a strongly typed language because each type of data, such as integer, character, hexadecimal, packed decimal etc. is predefined as part of the programming language, and all constants or variables defined for a given program must be declared with the specific data ty15 min readOperators in JavaJava OperatorsJava operators are special symbols that perform operations on variables or values. These operators are essential in programming as they allow you to manipulate data efficiently. They can be classified into different categories based on their functionality. In this article, we will explore different15 min readJava Arithmetic Operators with ExamplesOperators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they6 min readJava Assignment Operators with ExamplesOperators constitute the basic building block of any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they7 min readJava Unary Operator with ExamplesOperators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions be it logical, arithmetic, relational, etc. They are classified based on the functionality they p8 min readJava Relational Operators with ExamplesOperators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they10 min readJava Logical Operators with ExamplesLogical operators are used to perform logical "AND", "OR", and "NOT" operations, i.e., the functions similar to AND gate and OR gate in digital electronics. They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition under particular consider8 min readJava Ternary OperatorOperators constitute the basic building block of any programming language. Java provides many types of operators that can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provi5 min readBitwise Operators in JavaIn Java, Operators are special symbols that perform specific operations on one or more than one operands. They build the foundation for any type of calculation or logic in programming.There are so many operators in Java, among all, bitwise operators are used to perform operations at the bit level. T6 min readPackages in JavaJava PackagesPackages in Java are a mechanism that encapsulates a group of classes, sub-packages, and interfaces. Packages are used for: Prevent naming conflicts by allowing classes with the same name to exist in different packages, like college.staff.cse.Employee and college.staff.ee.Employee.They make it easie8 min readFlow Control in JavaDecision Making in Java (if, if-else, switch, break, continue, jump)Decision-making statements in Java execute a block of code based on a condition. Decision-making in programming is similar to decision-making in real life. In programming, we also face situations where we want a certain block of code to be executed when some condition is fulfilled.A programming lang10 min readJava if statementThe Java if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e. if a certain condition is true then a block of statements is executed otherwise not.Example:Java// Java program to illustrate If st5 min readJava if-else StatementThe if-else statement in Java is a powerful decision-making tool used to control the program's flow based on conditions. It executes one block of code if a condition is true and another block if the condition is false. In this article, we will learn Java if-else statement with examples.Example:Java/3 min readJava if-else-if ladder with ExamplesThe Java if-else-if ladder is used to evaluate multiple conditions sequentially. It allows a program to check several conditions and execute the block of code associated with the first true condition. If none of the conditions are true, an optional else block can execute as a fallback.Example: The b3 min readLoops in JavaJava LoopsLooping in programming languages is a feature that facilitates the execution of a set of instructions repeatedly while some condition evaluates to true. Java provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and condition7 min readJava For LoopJava for loop is a control flow statement that allows code to be executed repeatedly based on a given condition. The for loop in Java provides an efficient way to iterate over a range of values, execute code multiple times, or traverse arrays and collections.Now let's go through a simple Java for lo4 min readJava while LoopJava while loop is a control flow statement used to execute the block of statements repeatedly until the given condition evaluates to false. Once the condition becomes false, the line immediately after the loop in the program is executed.Let's go through a simple example of a Java while loop:Javapub3 min readJava Do While LoopJava do-while loop is an Exit control loop. Unlike for or while loop, a do-while check for the condition after executing the statements of the loop body.Example:Java// Java program to show the use of do while loop public class GFG { public static void main(String[] args) { int c = 1; // Using do-whi4 min readFor-Each Loop in JavaThe for-each loop in Java (also called the enhanced for loop) was introduced in Java 5 to simplify iteration over arrays and collections. It is cleaner and more readable than the traditional for loop and is commonly used when the exact index of an element is not required.Example: Using a for-each lo8 min readJump Statements in JavaJava Continue StatementIn Java, the continue statement is used inside the loops such as for, while, and do-while to skip the current iteration and move directly to the next iteration of the loop.Example:Java// Java Program to illustrate the use of continue statement public class Geeks { public static void main(String args4 min readJava Break StatementThe Break Statement in Java is a control flow statement used to terminate loops and switch cases. As soon as the break statement is encountered from within a loop, the loop iterations stop there, and control returns from the loop immediately to the first statement after the loop. Example:Java// Java3 min readJava return Keywordreturn keyword in Java is a reserved keyword which is used to exit from a method, with or without a value. The usage of the return keyword can be categorized into two cases:Methods returning a valueMethods not returning a value1. Methods Returning a ValueFor the methods that define a return type, th4 min readArrays in JavaArrays in JavaArrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me15+ min readJava Multi-Dimensional ArraysMultidimensional arrays are used to store the data in rows and columns, where each row can represent another individual array are multidimensional array. It is also known as array of arrays. The multidimensional array has more than one dimension, where each row is stored in the heap independently. T10 min readJagged Array in JavaIn Java, a Jagged array is an array that holds other arrays. When we work with a jagged array, one thing to keep in mind is that the inner array can be of different lengths. It is like a 2D array, but each row can have a different number of elements.Example:arr [][]= { {10,20}, {30,40,50,60},{70,80,6 min readStrings in JavaJava StringsIn Java, a String is the type of object that can store a sequence of characters enclosed by double quotes, and every character is stored in 16 bits, i.e., using UTF 16-bit encoding. A string acts the same as an array of characters. Java provides a robust and flexible API for handling strings, allowi9 min readString Class in JavaA string is a sequence of characters. In Java, objects of the String class are immutable, which means they cannot be changed once created. In this article, we are going to learn about the String class in Java.Example of String Class in Java:Java// Java Program to Create a String import java.io.*; cl7 min readStringBuffer Class in JavaThe StringBuffer class in Java represents a sequence of characters that can be modified, which means we can change the content of the StringBuffer without creating a new object every time. It represents a mutable sequence of characters.Features of StringBuffer ClassThe key features of StringBuffer c11 min readJava StringBuilder ClassIn Java, the StringBuilder class is a part of the java.lang package that provides a mutable sequence of characters. Unlike String (which is immutable), StringBuilder allows in-place modifications, making it memory-efficient and faster for frequent string operations.Declaration:StringBuilder sb = new7 min readOOPS in JavaJava OOP(Object Oriented Programming) ConceptsJava Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,13 min readClasses and Objects in JavaIn Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. The class represents a group of objects having similar properties and behavior, or in other words, we can say that a class is a blueprint for objects, wh11 min readJava MethodsJava Methods are blocks of code that perform a specific task. A method allows us to reuse code, improving both efficiency and organization. All methods in Java must belong to a class. Methods are similar to functions and expose the behavior of objects.Example: Java program to demonstrate how to crea8 min readAccess Modifiers in JavaIn Java, access modifiers are essential tools that define how the members of a class, like variables, methods, and even the class itself can be accessed from other parts of our program. They are an important part of building secure and modular code when designing large applications. Understanding de7 min readWrapper Classes in JavaA Wrapper class in Java is one whose object wraps or contains primitive data types. When we create an object in a wrapper class, it contains a field, and in this field, we can store primitive data types. In other words, we can wrap a primitive value into a wrapper class object. Let's check on the wr6 min readNeed of Wrapper Classes in JavaFirstly the question that hits the programmers is when we have primitive data types then why does there arise a need for the concept of wrapper classes in java. It is because of the additional features being there in the Wrapper class over the primitive data types when it comes to usage. These metho3 min read Like