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
36. Hierarchical Inheritance in Java
Now Reading
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
Inheritance is one of the fundamental concepts in object-oriented programming. Hierarchical inheritance in Java is a type of inheritance where the same class is inherited by more than one class.
In this kind of inheritance, the various classes gather their features from the same class. Read on to learn more about Java inheritance.
This tutorial will discuss why we use hierarchical inheritance in Java, important terminologies used in Java Inheritance, how hierarchical inheritance work in Java, why multiple inheritances are not supported in Java, the advantages and disadvantages of inheritance in Java, and much more.
Hierarchical inheritance is one of the most common and useful types of inheritance in Java. In this, classes inherit properties and behaviors from a single superclass but can have multiple subclasses that inherit from it. This creates a hierarchical relationship among the classes, forming a tree-like structure.
In Java, inheritance is implemented using the extends keyword. The syntax for creating a subclass that inherits from a superclass is as follows:
class Subclass extends Superclass {
// subclass members and methods
}
We need to familiarize ourselves with two main syntaxes when working with inheritance in Java.
Now, let us look at an example to understand hierarchical inheritance in Java. Suppose we have a superclass called Vehicle, which represents generic properties and behaviors of vehicles. It can have subclasses like Car, Motorcycle, and Truck, which inherit from it.
The Vehicle class can have common attributes and methods that apply to all types of vehicles, such as color, speed, start(), and stop(). Each subclass (Car, Motorcycle, and Truck) can also have its own specific attributes and methods.
Here is an example:
Code for main.java file:
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.color = "Red";
car.speed = 60;
car.numberOfDoors = 4;
car.start();
car.drive();
car.stop();
System.out.println("-----");
Motorcycle motorcycle = new Motorcycle();
motorcycle.color = "Black";
motorcycle.speed = 100;
motorcycle.hasSidecar = false;
motorcycle.start();
motorcycle.wheelie();
motorcycle.stop();
System.out.println("-----");
Truck truck = new Truck();
truck.color = "Blue";
truck.speed = 40;
truck.cargoCapacity = 5000;
truck.start();
truck.load();
truck.unload();
truck.stop();
}
}
Code for vehicle.java file:
class Vehicle {
String color;
int speed;
void start() {
// Code to start the vehicle
System.out.println("Vehicle started.");
}
void stop() {
// Code to stop the vehicle
System.out.println("Vehicle stopped.");
}
}
class Car extends Vehicle {
int numberOfDoors;
void drive() {
// Code to drive the car
System.out.println("Car is being driven.");
}
}
class Motorcycle extends Vehicle {
boolean hasSidecar;
void wheelie() {
// Code to perform a wheelie
System.out.println("Performing a wheelie.");
}
}
class Truck extends Vehicle {
int cargoCapacity;
void load() {
// Code to load the truck
System.out.println("Truck is being loaded.");
}
void unload() {
// Code to unload the truck
System.out.println("Truck is being unloaded.");
}
}
In this example, we create instances of the Car, Motorcycle, and Truck classes, set their attributes, and invoke their methods. The program outputs the corresponding messages to demonstrate the behavior of each class.
We can see how the subclasses Car, Motorcycle, and Truck inherit properties and methods from the Vehicle superclass. Each subclass also introduces its own unique attributes and methods, demonstrating the concept of hierarchical inheritance in Java.
Let us look at an example where we will achieve abstraction by defining an abstract superclass MediaPlayer that hides the implementation details of playing media and exposes only the essential methods (play(), stop()) and the abstract method displayMediaDetails().
The subclasses AudioPlayer and VideoPlayer inherit the common functionality from MediaPlayer and provide concrete implementations for displaying the details specific to audio and video media.
abstract class MediaPlayer {
private boolean isPlaying;
public void play() {
isPlaying = true;
System.out.println("Playing media...");
}
public void stop() {
isPlaying = false;
System.out.println("Stopped media.");
}
public abstract void displayMediaDetails();
}
class AudioPlayer extends MediaPlayer {
private String songTitle;
public AudioPlayer(String songTitle) {
this.songTitle = songTitle;
}
public void displayMediaDetails() {
System.out.println("Playing audio: " + songTitle);
}
}
class VideoPlayer extends MediaPlayer {
private String videoTitle;
public VideoPlayer(String videoTitle) {
this.videoTitle = videoTitle;
}
public void displayMediaDetails() {
System.out.println("Playing video: " + videoTitle);
}
}
public class Main {
public static void main(String[] args) {
AudioPlayer audioPlayer = new AudioPlayer("Song 1");
audioPlayer.play();
audioPlayer.displayMediaDetails();
audioPlayer.stop();
VideoPlayer videoPlayer = new VideoPlayer("Video 1");
videoPlayer.play();
videoPlayer.displayMediaDetails();
videoPlayer.stop();
}
}
In this example, MediaPlayer is an abstract class because it contains at least one abstract method (displayMediaDetails()) and cannot be instantiated directly. It defines common functionality for playing media and maintains a state (isPlaying) to track whether the media is being played or stopped.
Now, in the AudioPlayer subclass, we define a specific attribute songTitle and implement the displayMediaDetails() method to display the details of the currently playing audio. Similarly, in the VideoPlayer subclass, we define an attribute videoTitle and implement the displayMediaDetails() method to display the details of the currently playing video.
Now that we have learned about abstraction let us see an example of inheritance in Java that demonstrates encapsulation and hierarchical inheritance:
Code for main.java file:
public class Main {
public static void main(String[] args) {
Dog dog = new Dog("Buddy");
dog.eat(); // Accessing superclass method
dog.bark(); // Accessing subclass method
Cat cat = new Cat("Whiskers");
cat.eat(); // Accessing superclass method
cat.meow(); // Accessing subclass method
}
}
Code for animal.java file:
// Base class (superclass)
class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public void eat() {
System.out.println(name + " is eating.");
}
// Getter method for name
public String getName() {
return name;
}
}
// Derived class (subclass)
class Dog extends Animal {
public Dog(String name) {
super(name);
}
public void bark() {
System.out.println(getName() + " is barking.");
}
}
// Derived class (subclass)
class Cat extends Animal {
public Cat(String name) {
super(name);
}
public void meow() {
System.out.println(getName() + " is meowing.");
}
}
Polymorphism fundamentally allows objects from different classes to be treated like objects of common superclasses. In the case of hierarchical inheritance, multiple subclasses inherit from a single superclass, which creates a hierarchical relationship among the classes.
Here's a hierarchical inheritance example that explores polymorphism in Java:
Code for main.java file:
public class Main {
public static void main(String[] args) {
Animal animal1 = new Dog();
Animal animal2 = new Cat();
Animal animal3 = new Cow();
animal1.makeSound(); // Polymorphic method call
animal2.makeSound(); // Polymorphic method call
animal3.makeSound(); // Polymorphic method call
}
}
Code for animal.java file:
// Base class (superclass)
class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
}
// Derived class (subclass)
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("The dog barks");
}
}
// Derived class (subclass)
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("The cat meows");
}
}
// Derived class (subclass)
class Cow extends Animal {
@Override
public void makeSound() {
System.out.println("The cow moos");
}
}
Multiple inheritance in Java is not supported; it's like asking a creature to be physically present in two places at once, which violates the laws of nature.
Just like a person can have only one biological set of parents, a Java class can have only one direct superclass. Multiple inheritances can lead to conflicts and confusion when two superclasses define methods or variables with the same name.
Java avoids this complexity and opts for a simpler, more organized single inheritance model. So, in the case of Java, classes choose their superclasses wisely, embracing the elegance of simplicity over the perplexities of duality.
Here is a real-world example of hierarchical inheritance in Java:
class Shape {
public void draw() {
System.out.println("Drawing a shape");
}
}
class Rectangle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a rectangle");
}
}
class Circle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}
public class Main {
public static void main(String[] args) {
Shape shape1 = new Rectangle();
Shape shape2 = new Circle();
shape1.draw();
shape2.draw();
}
}
Inheritance provides several advantages in Java. Here are some key advantages:
While inheritance provides several advantages in Java, it also has some potential disadvantages that should be considered. Here are a few disadvantages of using inheritance:
A key concept in Java, hierarchical inheritance increases code modularity and reusability and reduces code length. This tutorial will assist you in understanding the concepts of hierarchical inheritance in Java with examples.
You can master Java and its various concepts with the help of online learning platforms like upGrad. Visit upGrad today to know more.
1. Can constructors be inherited in Java?
Constructors are not inherited in Java. However, the subclass can call the constructor of the superclass. It can do so using the "super" keyword to initialize the inherited members of the superclass.
2. What is method overriding in inheritance?
Method overriding is a feature of inheritance in Java. This allows a derived class to provide a different implementation for a method already defined in the base class. The method in the derived class must have the same name, return type, and parameters as the method in the base class.
3. Can a subclass access private members of the superclass in Java?
No, a subclass cannot directly access the superclass's private members (fields or methods). Private members are only accessible within the class they are defined in. However, they can be indirectly accessed using public or protected methods provided by the superclass.
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...