For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
45. Packages in Java
52. Java Collection
55. Generics In Java
56. Java Interfaces
59. Streams in Java
62. Thread in Java
66. Deadlock in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
77. JUnit Testing
80. Jar file in Java
81. Java Clean Code
85. Java 8 features
86. String in Java
92. HashMap in Java
97. Enum in Java
100. Hashcode in Java
104. Linked List in Java
108. Array Length in Java
110. Split in java
111. Map In Java
114. HashSet in Java
117. DateFormat in Java
120. Java List Size
121. Java APIs
127. Identifiers in Java
129. Set in Java
131. Try Catch in Java
132. Bubble Sort in Java
134. Queue in Java
141. Jagged Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
150. parseInt in Java
152. Abstraction in Java
153. String Input in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
163. Deque in Java
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
176. Square Root in Java
189. Javafx
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.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.