Java Program to Implement multiple inheritance
What is Multiple inheritance?
In this Article, We will write a Program to Implement multiple inheritance in Java.
Multiple inheritance is a feature of some object-oriented programming languages where a class can inherit properties and methods from multiple parent classes. In multiple inheritance, a derived class inherits from two or more base classes.
Multiple Inheritance:
Multiple inheritance can be useful in situations where a class needs to exhibit the properties and behaviors of more than one parent class. For example, a class representing a person might inherit properties and behaviors from both a class representing an employee and a class representing a student.
However, multiple inheritance can also lead to some programming challenges and complexity. One of the main challenges is the diamond problem, where a derived class inherits from two classes that both inherit from a common base class. This can cause ambiguity in the derived class about which inherited method to use.
To address this issue, some programming languages, such as Java, do not support multiple inheritance of classes, but instead support multiple inheritance of interfaces. An interface defines a set of methods that a class implementing the interface must implement. A class can implement multiple interfaces, allowing it to exhibit behaviors from multiple sources without the complexity and ambiguity of multiple inheritance of classes.
Java Program to Implement the graph data structure:
// Parent class A interface Printable { void print(); } // Parent class B interface Displayable { void display(); } // Child class implements parent classes A and B class MyClass implements Printable, Displayable{ // function of child class public void print() { System.out.println("Lakshit in Print Function"); } public void display() { System.out.println("Lakshit in Display Function"); } } class Main { public static void main(String[] args){ // MyClass object creation MyClass obj = new MyClass(); // function calling obj.print(); obj.display(); } }
Output: Lakshit in Print Function Lakshit in Display Function
In the above program, there are two interfaces, Printable and Displayable, each defining a single method. The class MyClass implements both interfaces, and provides its own implementations of the print and display methods. The Main class creates an object of MyClass and calls the print and display methods.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment