Tutorial Playlist
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.
Section | Description | Code Example |
Basic Concept of Inheritance | Explanation of how one class (subclass) can inherit properties and methods from another class (superclass). | class Parent { /*...*/ } class Child extends Parent { /*...*/ } |
Syntax of Inheritance in Java | Explain the extends keyword and how to define subclasses. | java<br>class Animal {<br> void eat() { ... }<br>}<br>class Dog extends Animal {<br> void bark() { ... }<br>}<br> |
Superclass and Subclass | Define superclass (parent class) and subclass (child class) relationships, and how to access superclass members in subclass. | super.methodName() example |
Method Overriding | Explain method overriding, and how a subclass can modify the behavior of methods inherited from the superclass. | java<br>class Animal {<br> void sound() { ... }<br>}<br>class Dog extends Animal {<br> @Override<br> void sound() { ... }<br>}<br> |
super Keyword | Discuss the usage of super to call superclass methods and constructors. | java<br>super(); // calling superclass constructor<br> |
Real-world Examples | Provide real-life scenarios where inheritance can be applied. | Example: Vehicle as superclass, Car and Bike as subclasses. |
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
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...