0% found this document useful (0 votes)
13 views12 pages

Understanding Inheritance in Java

Uploaded by

rockps12345
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views12 pages

Understanding Inheritance in Java

Uploaded by

rockps12345
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Inheritance in Java


••
Java, Inheritance is an important pillar of OOP(Object-Oriented Programming).
✓ Inheritance is a concept of OOPs where one class inherits from another class
that can reuse the methods and fields of the parent class.
✓ It is the mechanism in Java by which one class is allowed to inherit the
features(fields and methods) of another class.
✓ In Java, Inheritance means creating new classes based on existing ones.
✓ A class that inherits from another class can reuse the methods and fields of
that class. In addition, you can add new fields and methods to your current
class as well.
Why Do We Need Java Inheritance?
• Code Reusability: The code written in the Superclass is common to all
subclasses. Child classes can directly use the parent class code.
• Method Overriding: Method Overriding is achievable only through
Inheritance. It is one of the ways by which Java achieves Run Time
Polymorphism.
• Abstraction: The concept of abstract where we do not have to provide
all details is achieved through inheritance. Abstraction only shows the
functionality to the user.
Important Terminologies Used in Java Inheritance
• Class: Class is a set of objects which shares common characteristics/
behavior and common properties/ attributes. Class is not a real-world
entity. It is just a template or blueprint or prototype from which objects
are created.
• Super Class/Parent Class: The class whose features are inherited is
known as a superclass(or a base class or a parent class).
• Sub Class/Child Class/Extended Class/Derived class: The class that
inherits the other class is known as a subclass(or a derived class,
extended class, or child class). The subclass can add its own fields and
methods in addition to the superclass fields and methods.
• Reusability: Inheritance supports the concept of “reusability”, i.e.
when we want to create a new class and there is already a class that
includes some of the code that we want, we can derive our new class
from the existing class. By doing this, we are reusing the fields and
methods of the existing class.
How to Use Inheritance in Java?
The extends keyword is used for inheritance in Java. Using the extends keyword
indicates you are derived from an existing class. In other words, “extends” refers
to increased functionality.
Syntax :
class DerivedClass extends BaseClass
{
//methods and fields
}
Inheritance in Java Example
Example: In the below example of inheritance, class Bicycle is a base class, class
MountainBike is a derived class that extends the Bicycle class and class Test is a
driver class to run the program.

// Java program to illustrate the


// concept of inheritance

// base class
class Bicycle {
// the Bicycle class has two fields
public int gear;
public int speed;

// the Bicycle class has one constructor


public Bicycle(int gear, int speed)
{
[Link] = gear;
[Link] = speed;
}

// the Bicycle class has three methods


public void applyBrake(int decrement)
{
speed -= decrement;
}

public void speedUp(int increment)


{
speed += increment;
}

// toString() method to print info of Bicycle


public String toString()
{
return ("No of gears are " + gear + "\n"
+ "speed of bicycle is " + speed);
}
}

// derived class
class MountainBike extends Bicycle {

// the MountainBike subclass adds one more field


public int seatHeight;
// the MountainBike subclass has one constructor
public MountainBike(int gear, int speed,
int startHeight)
{
// invoking base-class(Bicycle) constructor
super(gear, speed);
seatHeight = startHeight;
}

// the MountainBike subclass adds one more method


public void setHeight(int newValue)
{
seatHeight = newValue;
}

// overriding toString() method


// of Bicycle to print more info
@Override public String toString()
{
return ([Link]() + "\nseat height is "
+ seatHeight);
}
}

// driver class
public class Test {
public static void main(String args[])
{

MountainBike mb = new MountainBike(3, 100, 25);


[Link]([Link]());
}
}

Output
No of gears are 3
speed of bicycle is 100
seat height is 25
In the above program, when an object of MountainBike class is created, a copy of
all methods and fields of the superclass acquires memory in this object. That is
why by using the object of the subclass we can also access the members of a
superclass.
Please note that during inheritance only the object of the subclass is created, not
the superclass. For more, refer to Java Object Creation of Inherited Class.
Example 2: In the below example of inheritance, class Employee is a base class,
class Engineer is a derived class that extends the Employee class and class Test is
a driver class to run the program.
• Java

// Java Program to illustrate Inheritance (concise)

import [Link].*;

// 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();
[Link]("Salary : " + [Link]
+ "\nBenefits : " + [Link]);
}
}

Output
Salary : 60000
Benefits : 10000
Illustrative image of the program:

In practice, inheritance, and polymorphism are used together in Java to achieve


fast performance and readability of code.
Java Inheritance Types
Below are the different types of inheritance which are supported by Java.
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
1. Single Inheritance
In single inheritance, subclasses inherit the features of one superclass. In the image
below, class A serves as a base class for the derived class B.

Single inheritance

• Java

// Java program to illustrate the


// concept of single inheritance
import [Link].*;
import [Link].*;
import [Link].*;

// Parent class
class One {
public void print_geek()
{
[Link]("Geeks");
}
}

class Two extends One {


public void print_for() { [Link]("for"); }
}

// Driver class
public class Main {
// Main function
public static void main(String[] args)
{
Two g = new Two();
g.print_geek();
g.print_for();
g.print_geek();
}
}

Output
Geeks
for
Geeks
2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class, and as well
as the derived class also acts as the base class for other classes. In the below image,
class A serves as a base class for the derived class B, which in turn serves as a base
class for the derived class C. In Java, a class cannot directly access
the grandparent’s members.

Multilevel Inheritance

• Java

// Java program to illustrate the


// concept of Multilevel inheritance
import [Link].*;
import [Link].*;
import [Link].*;

class One {
public void print_geek()
{
[Link]("Geeks");
}
}

class Two extends One {


public void print_for() { [Link]("for"); }
}

class Three extends Two {


public void print_geek()
{
[Link]("Geeks");
}
}

// Drived class
public class Main {
public static void main(String[] args)
{
Three g = new Three();
g.print_geek();
g.print_for();
g.print_geek();
}
}
Output
Geeks
for
Geeks
3. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more
than one subclass. In the below image, class A serves as a base class for the derived
classes B, C, and D.

• Java

// Java program to illustrate the


// concept of Hierarchical inheritance

class A {
public void print_A() { [Link]("Class A"); }
}

class B extends A {
public void print_B() { [Link]("Class B"); }
}

class C extends A {
public void print_C() { [Link]("Class C"); }
}

class D extends A {
public void print_D() { [Link]("Class D"); }
}

// Driver Class
public class Test {
public static void main(String[] args)
{
B obj_B = new B();
obj_B.print_A();
obj_B.print_B();

C obj_C = new C();


obj_C.print_A();
obj_C.print_C();

D obj_D = new D();


obj_D.print_A();
obj_D.print_D();
}
}

Output
Class A
Class B
Class A
Class C
Class A
Class D
4. Multiple Inheritance (Through Interfaces)
In Multiple inheritances, one class can have more than one superclass and inherit
features from all parent classes. Please note that Java does not support multiple
inheritances with classes. In Java, we can achieve multiple inheritances only
through Interfaces. In the image below, Class C is derived from interfaces A and B.

Multiple Inheritance

• Java

// Java program to illustrate the


// concept of Multiple inheritance
import [Link].*;
import [Link].*;
import [Link].*;

interface One {
public void print_geek();
}

interface Two {
public void print_for();
}

interface Three extends One, Two {


public void print_geek();
}
class Child implements Three {
@Override public void print_geek()
{
[Link]("Geeks");
}

public void print_for() { [Link]("for"); }


}

// Drived class
public class Main {
public static void main(String[] args)
{
Child c = new Child();
c.print_geek();
c.print_for();
c.print_geek();
}
}

Output
Geeks
for
Geeks
5. Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. Since Java doesn’t
support multiple inheritances with classes, hybrid inheritance involving multiple
inheritance is also not possible with classes. In Java, we can achieve hybrid
inheritance only through Interfaces if we want to involve multiple inheritance to
implement Hybrid inheritance.
However, it is important to note that Hybrid inheritance does not necessarily
require the use of Multiple Inheritance exclusively. It can be achieved through a
combination of Multilevel Inheritance and Hierarchical Inheritance with classes,
Hierarchical and Single Inheritance with classes. Therefore, it is indeed possible to
implement Hybrid inheritance using classes alone, without relying on multiple
inheritance type.

Java IS-A type of Relationship


IS-A is a way of saying: This object is a type of that object. Let us see how the
extends keyword is used to achieve inheritance.
• Java

public class SolarSystem {


}
public class Earth extends SolarSystem {
}
public class Mars extends SolarSystem {
}
public class Moon extends Earth {
}

Now, based on the above example, in Object-Oriented terms, the following are
true:-
• SolarSystem is the superclass of Earth class.
• SolarSystem is the superclass of Mars class.
• Earth and Mars are subclasses of SolarSystem class.
• Moon is the subclass of both Earth and SolarSystem classes.

• Java

class SolarSystem {
}
class Earth extends SolarSystem {
}
class Mars extends SolarSystem {
}
public class Moon extends Earth {
public static void main(String args[])
{
SolarSystem s = new SolarSystem();
Earth e = new Earth();
Mars m = new Mars();

[Link](s instanceof SolarSystem);


[Link](e instanceof Earth);
[Link](m instanceof SolarSystem);
}
}

Output
true
true
true

What Can Be Done in a Subclass?


In sub-classes we can inherit members as is, replace them, hide them, or
supplement them with new members:
• The inherited fields can be used directly, just like any other fields.
• We can declare new fields in the subclass that are not in the superclass.
• The inherited methods can be used directly as they are.
• We can write a new instance method in the subclass that has the same
signature as the one in the superclass, thus overriding it (as in the
example above, toString() method is overridden).
• We can write a new static method in the subclass that has the same
signature as the one in the superclass, thus hiding it.
• We can declare new methods in the subclass that are not in the
superclass.
• We can write a subclass constructor that invokes the constructor of the
superclass, either implicitly or by using the keyword super.
Advantages Of Inheritance in Java:
1. Code Reusability: Inheritance allows for code reuse and reduces the
amount of code that needs to be written. The subclass can reuse the
properties and methods of the superclass, reducing duplication of code.
2. Abstraction: Inheritance allows for the creation of abstract classes that
define a common interface for a group of related classes. This promotes
abstraction and encapsulation, making the code easier to maintain and
extend.
3. Class Hierarchy: Inheritance allows for the creation of a class hierarchy,
which can be used to model real-world objects and their relationships.
4. Polymorphism: Inheritance allows for polymorphism, which is the
ability of an object to take on multiple forms. Subclasses can override
the methods of the superclass, which allows them to change their
behavior in different ways.
Disadvantages of Inheritance in Java:
1. Complexity: Inheritance can make the code more complex and harder
to understand. This is especially true if the inheritance hierarchy is
deep or if multiple inheritances is used.
2. Tight Coupling: Inheritance creates a tight coupling between the
superclass and subclass, making it difficult to make changes to the
superclass without affecting the subclass.
Conclusion
Let us check some important points from the article are mentioned below:
• Default superclass: Except Object class, which has no superclass,
every class has one and only one direct superclass (single inheritance).
In the absence of any other explicit superclass, every class is implicitly
a subclass of the Object class.
• Superclass can only be one: A superclass can have any number of
subclasses. But a subclass can have only one superclass. This is because
Java does not support multiple inheritances with classes. Although with
interfaces, multiple inheritances are supported by Java.
• Inheriting Constructors: A subclass inherits all the members (fields,
methods, and nested classes) from its superclass. Constructors are not
members, so they are not inherited by subclasses, but the constructor
of the superclass can be invoked from the subclass.
• Private member inheritance: A subclass does not inherit the private
members of its parent class. However, if the superclass has public or
protected methods(like getters and setters) for accessing its private
fields, these can also be used by the subclass.

Common questions

Powered by AI

Abstract classes in Java serve as a blueprint for creating subclasses, providing a common interface to ensure consistent behavior across different subclasses while allowing each subclass to implement specific details. Inheritance is crucial in this context as it allows subclasses to extend these abstract classes, inheriting all defined abstract and implemented methods . This mechanism fosters abstraction by enabling the definition of common functionality that must be shared among subclasses while keeping implementation-specific methods open for refinement, promoting a flexible and organized code structure .

Java handles multiple inheritance through interfaces rather than classes. This approach is adopted because Java classes do not support multiple inheritance due to the complexities and potential conflicts involved with it . By using interfaces, Java allows a class to implement multiple interfaces, thereby achieving multiple inheritance without the ambiguities seen with multiple superclass inheritance. This method ensures a clean separation of methods across different interfaces, which a single class can implement and thus inherit multiple types .

The primary purpose of inheritance in Java is to promote code reusability, allowing developers to build new classes based on existing ones. This reusability reduces the need to duplicate code, leading to efficiency in development and ease of maintenance. By inheriting methods and fields from a superclass, a subclass can directly use existing functionality and also override or extend it to introduce new behavior . In addition to code reusability, inheritance facilitates polymorphism, enabling runtime method overriding, and supports abstraction by allowing the creation of abstract classes that provide a common interface for related classes . These features collectively promote efficient software development.

Java's IS-A relationship is fundamental in understanding the inheritance structure as it defines the connection that a derived class (subclass) has with its parent class (superclass). When a class inherits from another class using the 'extends' keyword, it signifies that the subclass is a type of the superclass, embodying an IS-A relationship . For instance, if 'Motorcycle' extends 'Vehicle', we can say a Motorcycle is a Vehicle. This relationship is critical in establishing polymorphism where different classes can be treated as instances of their superclass type, allowing for the dynamic assignment and manipulation of objects in a hierarchy .

Inheritance offers substantial advantages in forming a class hierarchy in Java by promoting code reusability, abstraction, and polymorphism. Code reusability is achieved as subclasses inherit fields and methods from superclasses, reducing redundancy and enhancing maintainability . Abstraction is supported as inheritance allows the creation of abstract classes defining a shared interface for multiple subclasses, fostering encapsulation and reducing complexity. Through polymorphism, inheritance enables objects to be treated as instances of their parent class, allowing flexible and scalable code design. These benefits establish a coherent and logical structure for class hierarchies, mirroring real-world relationships .

Method overriding in Java occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. This allows the subclass to offer tailored functionality while sticking to the same method signature, thus facilitating runtime polymorphism . The significance of this is profound as it allows objects to interact dynamically based on their runtime type, not their compile-time type, granting flexibility and modular design in applications. Through polymorphism, a single interface can represent multiple implementations, thereby enhancing the scalability and maintainability of code .

Multilevel inheritance in Java occurs when a class is derived from another derived class, creating a hierarchy that spans multiple levels. This form of inheritance is used to design frameworks or applications where components or classes require a progressive build-up of features or behaviors. For instance, consider a class 'Animal' with a subclass 'Mammal', which itself has a subclass 'Dog'. Each step expands on the previous, with 'Mammal' inheriting 'Animal's properties while adding its own, and 'Dog' inheriting both 'Animal's and 'Mammal's features . This structured inheritance facilitates reusable code and logical modeling of real-world hierarchies.

Hierarchical inheritance in Java occurs when a single class (the superclass) is extended by multiple subclasses . This type of inheritance models real-world relationships where multiple entities share common characteristics but also have their own distinct features. For example, consider a superclass 'Vehicle' with subclasses 'Car', 'Bicycle', and 'Truck'. Each subclass inherits common attributes and behaviors from 'Vehicle', like 'speed' or 'fuelCapacity', but can also add specific features such as 'numberOfDoors' for cars. Hierarchical inheritance allows for efficient modeling of such relationships by promoting code reuse and organization via a clear inheritance structure .

Method hiding occurs in Java when a static method in a subclass has the same signature as a static method in a superclass. Unlike method overriding, where the subclass method replaces the superclass method at runtime, method hiding resolves the call at compile time based on the reference type used. Method hiding is used typically with static methods, where objects' bindings to method calls depend on the class type, not the object itself . Conversely, method overriding allows dynamic method invocation where the method of the runtime object's actual class is invoked, promoting polymorphism and allowing behavior changes in subclass instances. Each has its use case: method hiding for controlling class-level behavior and access, overriding for instance-level flexibility .

While inheritance in Java offers numerous advantages, it also presents drawbacks, such as increased complexity and tight coupling. Complexity arises when deeply nested inheritance hierarchies make understanding and maintaining the code difficult . Tight coupling occurs because the subclass is dependent on the superclass, complicating changes to the inherited code; modifications in the superclass can inadvertently affect subclasses. Such drawbacks can lead to code fragility and hinder adaptability in software design, especially in systems requiring frequent changes or extension . Effective application of inheritance requires careful design to minimize these issues.

You might also like