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
Now Reading
35. Multiple Inheritance in Java
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 the ever-evolving landscape of object-oriented programming, Java stands tall as one of the most popular and powerful programming languages. At the heart of Java's success lies the concept of inheritance, a fundamental building block that empowers developers to create efficient, reusable, and modular code.
In this comprehensive guide, we will embark on a journey to unravel the depths of inheritance in Java. We will explore the practical implementation of inheritance, different types of inheritance supported by Java, and the advantages and disadvantages associated with its usage. By the end of this guide, you will possess the knowledge and insights to wield inheritance as a powerful tool in your Java programming endeavors.
Inheritance in Java is a technique that allows new classes to be derived from existing classes, inheriting their properties, methods, and behaviors. By leveraging inheritance, developers can build upon the foundation laid by existing classes, saving time and effort while promoting code reusability and extensibility.
Inheritance is essential in Java for several reasons including:
The visibility and use of classes, variables, methods, and constructors are determined by access modifiers in Java. They are essential in regulating access to inherited members and influencing how inheritance behaves. In Java, there are 4 access modifiers:
The public access modifier allows unrestricted access to a class, its members, and inherited members. Public members can be accessed from anywhere within the program, including external classes and packages.
The private access modifier restricts access to the class itself. Private members are not accessible outside the class in which they are declared, including subclasses. Therefore, private members cannot be inherited or accessed by subclasses. They are primarily used for encapsulation and to ensure data integrity within the class.
Within the same package and subclasses, even if they are in distinct packages, the protected access modifier permits access to the class, its members, and inherited members. A level of accessibility between public and private is offered by protected members. They are frequently used when you wish to restrict access to some classes while allowing access to subclasses in various packages.
The default access modifier is applied when no access modifier is explicitly specified. It allows access to the class, its members, and inherited members within the same package. Default members are not accessible to classes in different packages. This access modifier is useful when you want to limit the visibility of members to the package in which they are defined.
In Java, the super keyword is used to refer to the immediate parent class or superclass. It enables communication and interaction between a subclass and its superclass. It allows for the invocation of superclass constructors. It also gives access to superclass members and allows the overriding of superclass methods.
class Superclass
{
int i =20;
void display()
{
System.out.println(“Superclass display method”) ;
}
}
class Subclass extends Superclass
{
int i = 100;
void display()
{
super.display() ;
System.out.println(“Subclass display method”) ;
System.out.println(“ i value =”+i) ;
System.out.println(“superclass i value =”+super.i) ;
}
}
class SuperUse
{
public static void main(String args[ ] )
{
Subclass obj = new Subclass( ) ;
obj.display( ) ;
}
}
The super Keyword is used for the following purpose:
Here is a step-by-step guide to implementing inheritance in Java, especially if you are not an expert in the language.
You should create a superclass with shared attributes and methods for the subclasses as the initial step in this procedure. The superclass should then be given a suitable name before being declared using the class keyword. Attributes and methods from the superclass that you want the subclasses to inherit should be listed last.
The superclass is then expanded to produce subclasses. Use the extends keyword and the superclass name to accomplish this. Give the subclass a name that fits at this point and define it with the keyword. As a result, all non-private properties and methods from the superclass will be inherited by the subclass.
Take use of the opportunity to include new, subclass-specific characteristics and methods. You can override the inherited methods to give an alternative implementation that fits the particular requirements of the subclass. Declare a method with the same signature (name, return type, and parameters) in the subclass to override an existing one. If you want to make it clear that you're overriding the method on purpose, use the @Override annotation.
In the subclasses, you can directly access the inherited members (attributes and methods) from the superclass. You can use the dot notation (.) to access the superclass members because the public and private members of the superclass are accessible within the subclass.
Here, you provide unique functionality using the extra attributes and methods in the subclasses. Use the inherited members from the superclass as a starting point and build upon them.
Lastly, create objects of the subclasses and then test the inherited and overridden functionality. You should also invoke and access attributes from both the superclass and subclass objects. The following example shows inheritance in java example:
// Java Program to illustrate Inheritance (concise)
import java.io.*;
// Base or Super Class
class Employee {
int salary = 60000;
}
// Inherited or Sub Class
class Engineer extends Employee {
int benefits = 10000;
}
// Driver Class
class Gfg {
public static void main(String args[])
{
Engineer E1 = new Engineer();
System.out.println("Salary : " + E1.salary
+ "\nBenefits : " + E1.benefits);
}
}
There are several types of inheritance in Java, including single inheritance, multiple inheritance (through interfaces), and hybrid inheritance.
When a subclass extends a single superclass, this is referred to as single inheritance between two classes. The subclass inherits the superclass's attributes and methods under this type of inheritance. The following is the syntax for single inheritance:
A class can derive from various interfaces thanks to multiple inheritance. In Java, an interface outlines a contract for classes to adhere to specific behaviors. A class can inherit the constants and methods defined in several interfaces by implementing them.
Hybrid inheritance refers to a combination of single inheritance and multiple inheritance. It occurs when a class extends a superclass and implements multiple interfaces. This allows for the inheritance of attributes and methods from both the superclass and the interfaces.
A derived class will inherit a base class in multilevel inheritance, and in addition, the derived class will serve as the base class for subsequent classes. In the illustration below, class A acts as the base class for class B, which in turn acts as the base class for class C. A class in Java cannot access the members of the grandparents directly.
One class acts as the superclass (base class) for multiple subclasses in hierarchical inheritance. The base class for the derived classes B, C, and D in the figure below is class A.
In Java, inheritance is used to establish the IS-A relationship. It designates a subclass as a particular kind of its superclass. Designing a well-structured object-oriented system and exploiting inheritance efficiently require an understanding of the IS-A relationship.
public class SolarSystem {
}
public class Earth extends SolarSystem {
}
public class Mars extends SolarSystem {
}
public class Moon extends Earth {
}
A class is a specialized form of another class when there is an IS-A relationship, which is a manner of expressing inheritance. A subclass inherits characteristics and actions from its superclass in a hierarchical connection between classes. The substitutability principle, which states that an object of the subclass can be used anywhere an object of the superclass is anticipated, is the foundation of the IS-A relationship.
You may use inheritance effectively by understanding its benefits and using them to inform your design choices. The following are some benefits of using inheritance in Java:
Let's explore some of the common disadvantages of inheritance in Java:
In conclusion, inheritance in Java is a powerful mechanism that enables code organization, reusability, and extensibility. By understanding the concepts and considerations discussed in this guide, you can effectively leverage inheritance to create well-designed, modular, and maintainable Java applications. Embrace the wealth of possibilities that inheritance offers and cultivate it wisely to unlock the full potential of your Java programs.
1. What is the difference between 'extends' and 'implements' in Java inheritance?
In Java, 'extends' is used when one class inherits from another, enabling the reuse of fields and methods of the existing class. On the other hand, 'implements' is used when a class wants to adhere to a certain interface, meaning it must implement all methods declared in the interface.
2. What is polymorphism in Java?
Polymorphism in Java refers to the ability of an object to take on many forms. It allows objects of different classes to be treated as objects of a common superclass or interface. Polymorphism enables dynamic method binding and promotes code flexibility and reusability.
3. What is an example of inheritance?
An example of inheritance in Java is the relationship between a superclass "Vehicle" and its subclass "Car". The "Vehicle" class may have common attributes and methods for all vehicles, such as "startEngine()" and "stopEngine()". The "Car" class, as a subclass, can inherit these attributes and methods from the "Vehicle" class while also having its own unique attributes and methods specific to cars. The "Car" class extends or overrides the common functionality of a vehicle as necessary through inheritance.
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...