[go: up one dir, main page]

0% found this document useful (0 votes)
11 views11 pages

Chi 1

Uploaded by

raroy67751
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views11 pages

Chi 1

Uploaded by

raroy67751
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 11

Skip to content

geeksforgeeks
Courses 90% Refund
Tutorials
Java
Practice
Contests

Sign In

Java Arrays
Java Strings
Java OOPs
Java Collection
Java 8 Tutorial
Java Multithreading
Java Exception Handling
Java Programs
Java Project
Java Collections Interview
Java Interview Questions
Java MCQs
Spring
Spring MVC
Spring Boot
Hibernate

Content Improvement Event


Share Your Experiences
Java Tutorial
Overview of Java
Basics of Java
Input/Output in Java
Flow Control in Java
Operators in Java
Strings in Java
Arrays in Java
OOPS in Java
Inheritance in Java
Inheritance and Constructors in Java
Java and Multiple Inheritance
Interfaces and Inheritance in Java
Association, Composition and Aggregation in Java
Comparison of Inheritance in C++ and Java
Abstraction in Java
Encapsulation in Java
Polymorphism in Java
Constructors in Java
Methods in Java
Interfaces in Java
Wrapper Classes in Java
Keywords in Java
Access Modifiers in Java
Memory Allocation in Java
Classes of Java
Packages in Java
Java Collection Tutorial
Exception Handling in Java
Multithreading in Java
Synchronization in Java
File Handling in Java
Java Regex
Java IO
Java Networking
JDBC - Java Database Connectivity
Java 8 Features - Complete Tutorial
Java Backend DevelopmentCourse
Java and Multiple Inheritance
Last Updated : 16 Nov, 2022
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 Inheritance

Example 1:

// Java Program to Illustrate Unsupportance of


// Multiple Inheritance

// Importing input output classes


import java.io.*;

// Class 1
// First Parent class
class Parent1 {

// Method inside first parent class


void fun() {

// Print statement if this method is called


System.out.println("Parent1");
}
}

// Class 2
// Second Parent Class
class 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 classes
class Test extends Parent1, Parent2 {

// Main driver method


public static void main(String args[]) {

// Creating object of class in main() method


Test t = new Test();

// Trying to call above functions of class where


// Error is thrown as this class is inheriting
// multiple classes
t.fun();
}
}
Output: Compilation error is thrown

Conclusion: 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:

GrandParent
/ \
/ \
Parent1 Parent2
\ /
\ /
Test
The code is as follows

// Java Program to Illustrate Unsupportance of


// Multiple Inheritance
// Diamond Problem Similar Scenario

// Importing input output classes


import java.io.*;

// Class 1
// A Grand parent class in diamond
class GrandParent {

void fun() {

// Print statement to be executed when this method is called


System.out.println("Grandparent");
}
}

// Class 2
// First Parent class
class Parent1 extends GrandParent {
void fun() {

// Print statement to be executed when this method is called


System.out.println("Parent1");
}
}

// Class 3
// Second Parent Class
class Parent2 extends GrandParent {
void fun() {
// Print statement to be executed when this method is called
System.out.println("Parent2");
}
}

// Class 4
// Inheriting from multiple classes
class Test extends Parent1, Parent2 {

// Main driver method


public static void main(String args[]) {

// Creating object of this class i main() method


Test t = new Test();

// Now calling fun() method from its parent classes


// which will throw compilation error
t.fun();
}
}
Output:

Again it throws compiler error when run fun() method as multiple inheritances cause
a diamond problem when allowed in other languages like C++. From the code, we see
that: On calling the method fun() using Test object will cause complications such
as whether to call Parent1’s fun() or Parent2’s fun() method. Therefore, in order
to avoid such complications, Java does not support multiple inheritances of
classes.

Multiple inheritance is not supported by Java using classes, handling the


complexity that causes due to multiple inheritances is very complex. It creates
problems during various operations like casting, constructor chaining, etc, and the
above all reason is that there are very few scenarios on which we actually need
multiple inheritances, so better to omit it for keeping things simple and
straightforward.

How are the above problems handled for Default Methods and Interfaces?
Java 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 3:

// Java program to demonstrate Multiple Inheritance


// through default methods

// Interface 1
interface PI1 {

// Default method
default void show()
{

// Print statement if method is called


// from interface 1
System.out.println("Default PI1");
}
}

// Interface 2
interface PI2 {

// Default method
default void show()
{

// Print statement if method is called


// from interface 2
System.out.println("Default PI2");
}
}

// Main class
// Implementation class code
class TestClass implements PI1, PI2 {

// Overriding default show method


@Override
public void show()
{

// Using super keyword to call the show


// method of PI1 interface
PI1.super.show();//Should not be used directly in the main method;

// Using super keyword to call the show


// method of PI2 interface
PI2.super.show();//Should not be used directly in the main method;
}

//Method for only executing the show() of PI1


public void showOfPI1() {
PI1.super.show();//Should not be used directly in the main method;
}

//Method for only executing the show() of PI2


public void showOfPI2() {
PI2.super.show(); //Should not be used directly in the main method;
}

// Mai driver method


public static void main(String args[])
{

// Creating object of this class in main() method


TestClass d = new TestClass();
d.show();
System.out.println("Now Executing showOfPI1() showOfPI2()");
d.showOfPI1();
d.showOfPI2();
}
}
Output
Default PI1
Default PI2
Now Executing showOfPI1() showOfPI2()
Default PI1
Default PI2
Note: 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 4:

// 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();
}
}
Output
Default GPI

Three 90 Challenge is back on popular demand! After processing refunds worth INR
1CR+, we are back with the offer if you missed it the first time. Get 90% course
fee refund in 90 days. Avail now!
Want to be a master in Backend Development with Java for building robust and
scalable applications? Enroll in Java Backend and Development Live Course by
GeeksforGeeks to get your hands dirty with Backend Programming. Master the key Java
concepts, server-side programming, database integration, and more through hands-on
experiences and live projects. Are you new to Backend development or want to be a
Java Pro? This course equips you with all you need for building high-performance,
heavy-loaded backend systems in Java. Ready to take your Java Backend skills to the
next level? Enroll now and take your development career to sky highs.

https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks

232
Previous Article
Inheritance and Constructors in Java
Next Article
Interfaces and Inheritance in Java
Read More
Down Arrow
Similar Reads
Resolving Conflicts During Multiple Inheritance in Java
A class can implement multiple interfaces in java, but what if the implemented
multiple default interfaces have default methods with the same signatures? Then in
the implementing class, which of the default implementations would be invoked from
the several parent interfaces. Java 8 designers have been thinking about this
conflict and have specified
5 min read
How to Implement Multiple Inheritance by Using Interfaces in Java?
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 methods
with the same signature exist 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
2 min read
Why Java doesn't support Multiple Inheritance?
Multiple Inheritance is a feature provided by OOPS, it helps us to create a class
that can inherit the properties from more than one parent. Some of the programming
languages like C++ can support multiple inheritance but Java can't support multiple
inheritance. This design choice is rooted in various reasons including complexity
management, ambigui
5 min read
Multiple Inheritance in C++
Multiple Inheritance is a feature of C++ where a class can inherit from more than
one classes. The constructors of inherited classes are called in the same order in
which they are inherited. For example, in the following program, B's constructor is
called before A's constructor. A class can be derived from more than one base
class. Eg: (i) A CHILD
5 min read
Difference between Inheritance and Composition in Java
Inheritance: When we want to create a new class and there is already a class that
includes some of the code that we want, we can derive our new class from the
existing class. In doing this, we can reuse the fields and methods of the existing
class without having to write them ourself. A subclass inherits all the members
(fields, methods, and nested
3 min read
Difference between Inheritance and Interface in Java
Java is one of the most popular and widely used programming languages. Java has
been one of the most popular programming languages for many years. Java is Object
Oriented. However, it is not considered as a pure object-oriented as it provides
support for primitive data types (like int, char, etc). In this article, we will
understand the difference
3 min read
Illustrate Class Loading and Static Blocks in Java Inheritance
Class loading means reading .class file and store corresponding binary data in
Method Area. For each .class file, JVM will store corresponding information in
Method Area. Now incorporating inheritance in class loading. In java inheritance,
JVM will first load and initialize the parent class and then it loads and
initialize the child class. Example
3 min read
Interfaces and Inheritance in Java
A class can extend another class and can implement one and more than one Java
interface. Also, this topic has a major influence on the concept of Java and
Multiple Inheritance. Note: This Hierarchy will be followed in the same way, we
cannot reverse the hierarchy while inheritance in Java. This means that we cannot
implement a class from the interf
7 min read
Inheritance and Constructors in Java
Constructors in Java are used to initialize the values of the attributes of the
object serving the goal to bring Java closer to the real world. We already have a
default constructor that is called automatically if no constructor is found in the
code. But if we make any constructor say parameterized constructor in order to
initialize some attributes
3 min read
Comparison of Inheritance in C++ and Java
The purpose of inheritance is the same in C++ and Java. Inheritance is used in both
languages for reusing code and/or creating an ‘is-a’ relationship. The following
examples will demonstrate the differences between Java and C++ that provide support
for inheritance. 1) In Java, all classes inherit from the Object class directly or
indirectly. Theref
4 min read
Article Tags :
Java
School Programming
java-inheritance
Practice Tags :
Java
three90RightbarBannerImg
course-img
215k+ interested Geeks
Master Java Programming - Complete Beginner to Advanced
Avail 90% Refund
course-img
214k+ interested Geeks
JAVA Backend Development - Live
Avail 90% Refund
course-img
30k+ interested Geeks
Manual to Automation Testing: A QA Engineer's Guide
Avail 90% Refund
geeksforgeeks-footer-logo
Corporate & Communications Address:- A-143, 9th Floor, Sovereign Corporate Tower,
Sector- 136, Noida, Uttar Pradesh (201305) | Registered Address:- K 061, Tower K,
Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh,
201305
GFG App on Play Store
GFG App on App Store
Company
About Us
Legal
Careers
In Media
Contact Us
Advertise with us
GFG Corporate Solution
Placement Training Program
Explore
Job-A-Thon Hiring Challenge
Hack-A-Thon
GfG Weekly Contest
Offline Classes (Delhi/NCR)
DSA in JAVA/C++
Master System Design
Master CP
GeeksforGeeks Videos
Geeks Community
Languages
Python
Java
C++
PHP
GoLang
SQL
R Language
Android Tutorial
DSA
Data Structures
Algorithms
DSA for Beginners
Basic DSA Problems
DSA Roadmap
DSA Interview Questions
Competitive Programming
Data Science & ML
Data Science With Python
Data Science For Beginner
Machine Learning Tutorial
ML Maths
Data Visualisation Tutorial
Pandas Tutorial
NumPy Tutorial
NLP Tutorial
Deep Learning Tutorial
Web Technologies
HTML
CSS
JavaScript
TypeScript
ReactJS
NextJS
NodeJs
Bootstrap
Tailwind CSS
Python Tutorial
Python Programming Examples
Django Tutorial
Python Projects
Python Tkinter
Web Scraping
OpenCV Tutorial
Python Interview Question
Computer Science
GATE CS Notes
Operating Systems
Computer Network
Database Management System
Software Engineering
Digital Logic Design
Engineering Maths
DevOps
Git
AWS
Docker
Kubernetes
Azure
GCP
DevOps Roadmap
System Design
High Level Design
Low Level Design
UML Diagrams
Interview Guide
Design Patterns
OOAD
System Design Bootcamp
Interview Questions
School Subjects
Mathematics
Physics
Chemistry
Biology
Social Science
English Grammar
Commerce
Accountancy
Business Studies
Economics
Management
HR Management
Finance
Income Tax
Databases
SQL
MYSQL
PostgreSQL
PL/SQL
MongoDB
Preparation Corner
Company-Wise Recruitment Process
Resume Templates
Aptitude Preparation
Puzzles
Company-Wise Preparation
Companies
Colleges
Competitive Exams
JEE Advanced
UGC NET
UPSC
SSC CGL
SBI PO
SBI Clerk
IBPS PO
IBPS Clerk
More Tutorials
Software Development
Software Testing
Product Management
Project Management
Linux
Excel
All Cheat Sheets
Recent Articles
Free Online Tools
Typing Test
Image Editor
Code Formatters
Code Converters
Currency Converter
Random Number Generator
Random Password Generator
Write & Earn
Write an Article
Improve an Article
Pick Topics to Write
Share your Experiences
Internships
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By
using our site, you acknowledge that you have read and understood our Cookie Policy
& Privacy Policy
Got It !
Lightbox

You might also like