Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
Now Reading
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
In this digital age, Java has become one of the most widely used programming languages, renowned for its portability and robustness. One of the fundamental concepts in Java is OOPs, of which there are four pillars, abstraction, encapsulation, polymorphism, and inheritance.
So what is inheritance exactly? It is a Java attribute that allows the user to create new classes by inheriting characteristics from existing ones. This tutorial will focus on multiple inheritance in Java and explore its various uses.
Inheritance facilitates the creation of new classes that inherit attributes and behaviors from existing classes. It enables developers to establish connections between classes, fostering code reuse and promoting efficient development by managing time.
In lay terms, multiple inheritance in Java refers to the capability of a class to inherit properties from multiple interfaces, enabling code reuse, modularity, and versatility in class design.
Multiple inheritance in Java refers to the power of a class to inherit characteristics from more than one superclass at the same time. In the case of multiple inheritances, we can say that classes derive properties from multiple parent classes, thus forming class hierarchies.
Inheritance is a cornerstone concept In Java programming, offering many advantages and allowing efficient, modular, and reusable code. Here we will delve into the compelling reasons why Java developers widely embrace inheritance, exploring the key benefits it brings to the table.
This comprehensive guide will shed light on the essential and significant terms used in inheritance. By learning these terms, you'll gain clarity on the intricacies of inheritance and be able to wield its power effectively in your Java code. Let's explore the key terms associated with inheritance in Java.
The superclass or base class is the existing class from which other classes inherit properties and behaviors. It serves as the foundation for the derived classes and defines the common characteristics inherited by its subclasses
A subclass or derived class is a new class created by inheriting properties and behaviors from a superclass. It specializes in the working of the superclass by adding new features or modifying existing ones.
The "extends" keyword is used in Java to establish an inheritance relationship between classes. It allows a subclass to inherit from a superclass. By specifying the superclass after the "extends" keyword, the subclass gains access to all the public and protected members of the superclass
The "super" keyword in Java is used within a subclass to refer to its superclass. It can be used to access superclass members, invoke superclass constructors, and differentiate between superclass and subclass members with the same name.
Method overriding is when subclasses implement methods already defined in superclasses. By overriding a method, the subclass can customize or extend the behavior inherited from the superclass.
The "super()" constructor invocation is used in a subclass constructor to call the constructor of its superclass. It ensures that the superclass constructor is executed before the subclass constructor, allowing the initialization of inherited members.
The "final" keyword is used in Java to indicate that a class, method, or variable cannot be extended, overridden, or modified, respectively. When applied to a class, it prevents inheritance, making it the final class in the hierarchy.
Here is an example of inheritance in Java:
// Parent class
class Vehicle {
protected String brand;
protected int year;
public Vehicle(String brand, int year) {
this.brand = brand;
this.year = year;
}
public void honk() {
System.out.println("Honk honk!");
}
}
// Child class inheriting from Vehicle
class Car extends Vehicle {
private int numberOfDoors;
public Car(String brand, int year, int numberOfDoors) {
super(brand, year);
this.numberOfDoors = numberOfDoors;
}
public void drive() {
System.out.println("Driving the car");
}
}
// Child class inheriting from Vehicle
class Motorcycle extends Vehicle {
private boolean hasSidecar;
public Motorcycle(String brand, int year, boolean hasSidecar) {
super(brand, year);
this.hasSidecar = hasSidecar;
}
public void wheelie() {
System.out.println("Doing a wheelie!");
}
}
// Main class to test the inheritance
public class Main {
public static void main(String[] args) {
Car car = new Car("Toyota", 2020, 4);
car.honk();
car.drive();
Motorcycle motorcycle = new Motorcycle("Harley-Davidson", 2021, false);
motorcycle.honk();
motorcycle.wheelie();
}
}
In this example, we have a parent class called Vehicle with two instance variables brand and year, and a method honk(). The child classes Car and Motorcycle inherit from the Vehicle class.
The Car class adds an additional instance variable numberOfDoors and a method drive(). The Motorcycle class adds an additional instance variable hasSidecar and a method wheelie().
In the Main class, we create objects of the Car and Motorcycle classes and call their respective methods to demonstrate inheritance.
Apart from multiple inheritance, Java has three kinds of inheritance. Let us explore them.
Here is an example of single inheritance in Java:
// Parent class
class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public void eat() {
System.out.println(name + " is eating.");
}
}
// Child class inheriting from Animal
class Dog extends Animal {
public Dog(String name) {
super(name);
}
public void bark() {
System.out.println(name + " is barking.");
}
}
// Main class to test the single inheritance
public class Main {
public static void main(String[] args) {
Dog dog = new Dog("Buddy");
dog.eat();
dog.bark();
}
}
In this example, we have a parent class called Animal with an instance variable name and a method eat(). The child class Dog inherits from the Animal class.
The Dog class adds a method bark(). It can access the name variable and the eat() method from the parent class.
In the Main class, we create an object of the Dog class and call its methods to demonstrate single inheritance.
Here is an example of multilevel inheritance in Java:
// Grandparent class
class Animal {
protected String species;
public Animal(String species) {
this.species = species;
}
public void eat() {
System.out.println(species + " is eating.");
}
}
// Parent class inheriting from Animal
class Dog extends Animal {
public Dog() {
super("Dog");
}
public void bark() {
System.out.println("Dog is barking.");
}
}
// Child class inheriting from Dog
class Labrador extends Dog {
public Labrador() {
System.out.println("Labrador is a type of Dog.");
}
public void playFetch() {
System.out.println("Labrador is playing fetch.");
}
}
// Main class to test the multilevel inheritance
public class Main {
public static void main(String[] args) {
Labrador labrador = new Labrador();
labrador.eat();
labrador.bark();
labrador.playFetch();
}
}
In this example, we have a grandparent class called Animal with an instance variable species and a method eat(). The parent class Dog inherits from the Animal class and adds a method bark(). The child class Labrador inherits from the Dog class and adds a method playFetch().
In the Main class, we create an object of the Labrador class and call its methods to demonstrate multilevel inheritance.
Here is an example of hierarchical inheritance in Java:
// Parent class
class Animal {
protected String species;
public Animal(String species) {
this.species = species;
}
public void eat() {
System.out.println(species + " is eating.");
}
}
// Child class 1 inheriting from Animal
class Dog extends Animal {
public Dog() {
super("Dog");
}
public void bark() {
System.out.println("Dog is barking.");
}
}
// Child class 2 inheriting from Animal
class Cat extends Animal {
public Cat() {
super("Cat");
}
public void meow() {
System.out.println("Cat is meowing.");
}
}
// Main class to test the hierarchical inheritance
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
dog.bark();
Cat cat = new Cat();
cat.eat();
cat.meow();
}
}
In this example, we have a parent class called Animal with an instance variable species and a method eat(). The child class Dog inherits from the Animal class and adds a method bark(). The child class Cat also inherits from the Animal class and adds a method meow().
In the Main class, we create objects of the Dog and Cat classes and call their respective methods to demonstrate hierarchical inheritance.
Java does not directly support multiple inheritance, where classes can inherit from multiple parent classes. However, you can achieve similar functionality using interfaces in Java.
Here's an example code that demonstrates a workaround for achieving multiple inheritance-like behavior using interfaces:
// First parent interface
interface Animal {
void eat();
}
// Second parent interface
interface Mammal {
void run();
}
// Child class implementing both interfaces
class Dog implements Animal, Mammal {
@Override
public void eat() {
System.out.println("Dog is eating.");
}
@Override
public void run() {
System.out.println("Dog is running.");
}
}
// Main class to test multiple inheritance-like behavior
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
dog.run();
}
}
In this example, we have two parent interfaces: Animal and Mammal. The Animal interface declares the eat() method, and the Mammal interface declares the run() method.
The Dog class implements the Animal and Mammal interfaces, effectively inheriting from both. It provides implementations for the eat() and run() methods.
In the Main class, we create an object of the Dog class and call its methods to demonstrate multiple inheritance-like behavior.
Java intentionally omits multiple inheritance. Let's examine the rationale behind Java's decision to exclude multiple inheritance.
Java avoids the diamond problem and maintains code stability by excluding multiple inheritance.
This design choice enhances code clarity, modularity, and extensibility, allowing developers to compose classes using interfaces and achieve similar benefits to multiple inheritance without the associated complexities.
As a language, Java does not support multiple inheritance to maintain simplicity. However, developers can utilize alternative techniques to achieve similar benefits while keeping the code’s clarity and maintainability.
Understanding these alternatives to multiple inheritance in Java helps developers to design maintainable code structures. By using such composition, interface-based inheritance, and the principle of composition over inheritance, developers can get code flexibility without any complexities associated with multiple inheritance.
1. Why doesn't Java support multiple inheritance?
Java avoids multiple inheritance to maintain code simplicity and avoid any unnecessary bugs.
2. What are the alternatives to multiple inheritance in Java?
Alternatives to multiple inheritance in Java include composition, interface-based inheritance, and the principle of composition over inheritance.
3. Can multiple inheritance be achieved in Java using interfaces?
No, multiple inheritance cannot be achieved directly in Java using interfaces. However, classes can perform multiple interfaces, achieving similar results.
4. How can I overcome the limitations of multiple inheritance in Java?
The issues of multiple inheritance in Java can be solved by adding design patterns like the Adapter pattern or using composition and delegation to combine functions from multiple classes.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...