0% found this document useful (0 votes)
21 views18 pages

Understanding Java Inheritance Basics

Inheritance in Java allows a class (subclass) to inherit properties and methods from another class (superclass), representing an IS-A relationship. It promotes code reusability and supports method overriding for runtime polymorphism. Java supports various types of inheritance, including single, multilevel, hierarchical, multiple (through interfaces), and hybrid inheritance, while also introducing concepts like abstract classes and interfaces for achieving abstraction and loose coupling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views18 pages

Understanding Java Inheritance Basics

Inheritance in Java allows a class (subclass) to inherit properties and methods from another class (superclass), representing an IS-A relationship. It promotes code reusability and supports method overriding for runtime polymorphism. Java supports various types of inheritance, including single, multilevel, hierarchical, multiple (through interfaces), and hybrid inheritance, while also introducing concepts like abstract classes and interfaces for achieving abstraction and loose coupling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

What is Inheritance?

Java enables a class to inherit properties and actions from another class called as
inheritance. Through inheritance, a subclass can access members of its superclass (fields and

methods),

Inheritance represents the IS-A relationship which is also known as a parent-child


relationship. E.g. A kiwi is a fruit

Why use inheritance?

o For Method Overriding (so runtime polymorphism can be achieved).

o For Code Reusability.

Terms used in Inheritance

o Class: A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created.

o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called
a derived class, extended class, or child class.

o Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.

o Reusability: As the name specifies, reusability is a mechanism which facilitates you to


reuse the fields and methods of the existing class when you create a new class. You
can use the same fields and methods already defined in the previous class.

The Syntax of Java Inheritance class Subclass-

name extends Superclass-name

//methods and fields

The extends keyword indicates that we are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.

Java Inheritance Example

class Employee{

float salary=40000; }
class Programmer extends Employee{

int bonus=10000;

public class Main{ public static void

main(String args[]){

Programmer p=new Programmer();

[Link]("Programmer salary is:"+[Link]);

[Link]("Bonus of Programmer is:"+[Link]);

Output:

Programmer salary is:40000.0

Bonus of programmer is:10000

Types of Inheritance in Java

In Java programming, multiple and hybrid inheritance is supported through interface only.

[Link] Inheritance

When a class inherits another class, it is known as a single inheritance.

In the example given below, Dog class inherits the Animal class, so there is the single
inheritance.
Example

class Animal{ void

eat() {

[Link]("eating...");

class Dog extends Animal{ void

bark(){

[Link]("barking...");

public class Main{ public static void

main(String args[]){ Dog d=new

Dog();

[Link]();

[Link]();

Output:

barking...

eating...

[Link] Inheritance

When there is a chain of inheritance, it is known as multilevel inheritance.

As you can see in the example given below, BabyDog class inherits the Dog class which again
inherits the Animal class, so there is a multilevel inheritance.

To read more: Multilevel Inheritance in Java


Example

class Animal{ void

eat(){

[Link]("eating...");

class Dog extends Animal{ void

bark(){

[Link]("barking...");

class BabyDog extends Dog{

void weep(){

[Link]("weeping...");

public class Main{ public static void

main(String args[]){ BabyDog

d=new BabyDog();
[Link]();

[Link]();

[Link]();

Output:

weeping...

barking...

eating...

[Link] Inheritance

When two or more classes inherits a single class, it is known as hierarchical inheritance.

In the example given below, Dog and Cat classes inherits the Animal class, so there is
hierarchical inheritance.

Example

class Animal{ void eat()

{[Link]("eating...");}

class Dog extends Animal{ void bark()

{[Link]("barking...");}

class Cat extends Animal{ void meow()

{[Link]("meowing...");}
}

public class Main{ public static void

main(String args[]){ Cat c=new

Cat();

[Link]();

[Link]();

[Link]();

Output:

meowing...

eating...

[Link] Inheritance

Multiple Inheritance A class's capacity to inherit traits from several classes is referred to as
multiple inheritances.

Multiple inheritances, however, can result in issues like the diamond problem, which occurs
when two superclasses share the same method or field and causes conflicts. Java uses
interfaces to implement multiple inheritances in order to prevent these conflicts.

Example

interface Character {

void attack();

}
interface Weapon {

void use();

class Warrior implements Character, Weapon {

public void attack() {

[Link]("Warrior attacks with a sword.");

public void use() {

[Link]("Warrior uses a sword.");

class Mage implements Character, Weapon {

public void attack() {

[Link]("Mage attacks with a wand.");

public void use() {

[Link]("Mage uses a wand.");

public class Main { public static

void main(String[] args) {

Warrior warrior = new Warrior(); Mage mage =

new Mage(); [Link](); // Output: Warrior

attacks with a sword. [Link](); // Output: Warrior

uses a sword. [Link](); // Output: Mage attacks

with a wand. [Link](); // Output: Mage uses a

wand.

}
}

Output:

Warrior attacks with a sword.

Warrior uses a sword.

Mage attacks with a wand.

Mage uses a wand.

How to achieve Multiple Inheritance in Java?

Java supports multiple inheritance through interfaces only, where a class can implement
multiple interfaces. Multiple inheritance in Java is not possible by class, but it is possible
through interfaces.

[Link] Inheritance in Java

The hybrid inheritance is the composition of two or more types of inheritance. The main
purpose of using hybrid inheritance is to modularize the code into well-defined classes. It
also provides the code reusability.

The hybrid inheritance can be achieved by using the following combinations:

o Single and Multiple Inheritance (not supported but can be achieved


through interface) o Multilevel and Hierarchical Inheritance o
Hierarchical and Single Inheritance o Multiple and Multilevel
Inheritance

Example:

class C

public void disp()

[Link]("C");

class A extends C

public void disp()

[Link]("A");

class B extends C

public void disp()

[Link]("B");

public class D extends A

public void disp()

{
[Link]("D");

public static void main(String args[])

D obj = new D(); [Link]();

Output:

Abstract Class in Java

An abstract class in Java acts as a partially implemented class that itself cannot be
instantiated.

It exists only for subclassing purposes, and provides a template for its subcategories to
follow.

Abstract classes can have implementations with abstract methods.

Abstract methods are declared to have no body, leaving their implementation to subclasses.
Abstract Method in Java

A method which is declared as abstract and does not have implementation is known as an
abstract method.

Example of abstract method abstract void printStatus();//no

method body and abstract

Example of Abstract Class that has an Abstract Method

Example

//Creating an abstract class having abstract method

abstract class Bike{

abstract void run();

//Creating a child class and override abstract

method class Honda extends Bike{ void run()

{[Link]("running safely");}

//Creating a Main class to create object and call

methods public class Main{ public static void

main(String args[]){ Bike obj = new Honda();

[Link]();

Output:

running safely

Abstract Class having Constructor, Data Member and Methods

An abstract class can have a data member, abstract method, method body (non-abstract
method), constructor, and even main() method. Example
abstract class Bike{

Bike(){[Link]("bike is created");}

abstract void run(); void changeGear()

{[Link]("gear changed");}

//Creating a Child class which inherits Abstract class class

Honda extends Bike{

void run(){[Link]("running safely..");}

//Creating a Main class which calls abstract and non-abstract methods

public class Main{ public static void main(String args[]){ Bike

obj = new Honda(); [Link](); [Link]();

Output:

bike is created

running safely..

gear changed

Key Features of Abstract Classes

Abstract Methods: Abstract classes can have abstract methods, which are declared without
a body. Subclasses must provide concrete implementations for these methods.

Concrete Methods: Abstract classes can also contain concrete methods with defined
behavior. Subclasses inherit these methods along with their implementations.

Cannot be Instantiated: Abstract classes cannot be instantiated directly. They serve as a


blueprint for other classes and must be extended to be used.
Can Have Constructors: Abstract classes can have constructors, which are invoked when a
subclass object is created. These constructors are used to initialize the state of the
abstract class.

Interface in Java

• An interface in Java is a blueprint of a class. It has static constants and abstract


methods.

• There can be only abstract methods in the Java interface, not a method body.
Why use a Java interface?

There are mainly three reasons to use an interface. They are given below.

o It is used to achieve abstraction.

o By interface, we can support the functionality of multiple inheritance.

o It is used to achieve loose coupling.

How to declare an interface?

• An interface is declared by using the interface keyword.


• It provides total abstraction; it means all the methods in an interface are declared
with an empty body, and all the fields are public, static and final by default.
• A class that implements an interface must implement all the methods declared in the
interface.

Syntax:

interface interface_name{

// declare constant fields //

declare methods that abstract

// by default.

Declaring Interface

interface Animal {

void eat(); void

sleep();
}

Relationship Between Classes and Interfaces

Java Interface Example

//Creating an interface

interface Printable{

void print();

//Creating a class that implements Printable

class Printer implements Printable{ public

void print(){[Link]("Hello");}

//Creating a class that creates objects and call

methods public class Main{ public static void

main(String args[]){ Printable p=new Printer();

[Link]();

Output:

Hello

Multiple Inheritance in Java by Interface


If a class implements multiple interfaces, or an interface extends multiple interfaces, it is
known as multiple inheritance.

Example

//Creating two interfaces

interface Printable{

void print();

interface Showable{

void show();

//Creating a class that implements two interfaces class

Computer implements Printable,Showable{ public void

print(){[Link]("printing data...");} public

void show(){[Link]("showing data...");}

//Creating a Main class to create object and call methods

public class Main{ public static void main(String

args[]){ Computer c = new Computer();

[Link]();

[Link]();

Output:
printing data...

showing data...

Inheritance of Interfaces

A class implements an interface, but one interface can extend another interface.

Example

interface Printable{ void

print();

interface Showable extends Printable{ void

show();

class Main implements Showable{ public void

print(){[Link]("Hello");} public void

show(){[Link]("Welcome");}

public static void main(String args[]){ Main

obj = new Main();

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

Output:

Hello

Welcome

Difference between Abstract Class and Interface in Java

Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods.

Abstract class and interface both can't be instantiated.


Abstract class Interface

1) Abstract class can have abstract and Interface can have only abstract methods. Since
nonabstract methods. Java 8, it can have default and static methods
also.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non-final, static Interface has only static and final variables.
and non-static variables.

4) Abstract class can provide the implementation Interface can't provide the implementation of
of interface. abstract class.

5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.

6) An abstract class can extend another Java class An interface can extend another Java interface
and implement multiple Java interfaces. only.

7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".

8) A Java abstract class can have class members Members of a Java interface are public by
like private, protected, etc. default.
9)Example: Example: public interface
public abstract class Shape{ public Drawable{ void draw();
abstract void draw(); }
}

Common questions

Powered by AI

Java achieves polymorphism primarily through inheritance and interfaces, enabling objects to be treated as instances of their superclass or interfaces, rather than their actual class . Method overriding plays a critical role in polymorphism by allowing subclasses to provide specific implementations of methods already defined in the superclass or interface. This means that different classes can perform distinct behaviors through a common interface or base class reference, such as calling different versions of an overridden method based on the actual object type at runtime . This ability to override methods increases flexibility and allows dynamic method invocation, enhancing the ability to design systems that are scalable and adaptable to change. Interfaces contribute by specifying contractual behaviors that can be implemented by any class, further enabling polymorphic behavior among unrelated classes .

Hierarchical inheritance in Java occurs when multiple classes inherit from a single superclass. An example is when the "Dog" and "Cat" classes both extend the "Animal" class . This allows each subclass to have access to the same methods and fields defined in the "Animal" class, such as "eat()". Hierarchical inheritance is useful because it enables code reusability and promotes organized code structure by applying shared behavior across subclasses while allowing each subclass to implement or extend behaviors as needed .

An abstract class in Java can have both abstract and concrete methods, meaning it can provide a default behavior or state to shared characteristics of sub-classes, while also defining methods for the subclasses to implement . Interfaces, on the other hand, can contain only abstract methods (prior to Java 8) and static or default methods. Abstract classes are suitable when a base class is needed to provide common functionality and share common attributes among subclasses. Interfaces are ideal for defining a contract for disparate classes, allowing multiple inheritance of behavior without state . Additionally, interfaces help achieve polymorphism by enabling different classes to implement the same set of methods, promoting loose coupling and flexibility in system design .

Java supports multiple inheritance through interfaces because a class in Java can implement multiple interfaces, thereby inheriting the abstract methods declared in them . This approach avoids the diamond problem seen in languages that allow multiple class inheritance, where ambiguity can arise from inheriting the same method from multiple base classes . By using interfaces, Java enables a form of multiple inheritance while ensuring that the implementation of methods remains clear and unambiguous, as each class must provide its concrete implementations of the interface methods .

Java provides abstraction through abstract classes and interfaces. Abstract classes act as blueprints for subclasses, containing both defined (concrete) methods and undefined (abstract) methods that must be implemented by subclasses . Interfaces, on the other hand, define a contract that implementing classes must adhere to, using only abstract methods (prior to Java 8). Together, they complement each other by allowing developers to separate concerns: abstract classes provide a way to share code among related classes, while interfaces enable implementation of methods across disparate classes promoting flexible, modular design. This combination enhances encapsulation, reduces complexity and allows a high level of abstraction, which are essential for building maintainable, scalable systems .

Methods inside abstract classes serve as a blueprint for subclasses to implement specific behaviors, representing incomplete functionality that derived classes must complete. Meanwhile, concrete methods provide shared behavior that can be reused by subclasses, eliminating the need for repeated code . Unlike a concrete class that typically represents fully-implemented objects, an abstract class enforces a contract for subclasses to provide specific functionality, while allowing some default behavior through concrete methods. This design promotes code reuse and ensures consistent implementation across related classes, especially useful when a group of classes should adhere to certain behavior while sharing some common operational logic .

Abstract methods in Java specify methods with no body, serving as a placeholder that subclasses must implement, thus enforcing a contract for subclasses to follow . They are effectively employed in scenarios where a common interface across different classes is necessary, yet the actual implementation varies significantly. For example, when creating a hierarchy of graphical objects where computation or drawing logic might differ vastly, but all objects must expose a "draw()" method—the abstract method provides a way to mandate this behavior while keeping implementation details flexible and class-specific .

Inheritance in Java provides significant benefits, including method overriding and code reusability. Method overriding is crucial for achieving runtime polymorphism, allowing subclasses to modify methods defined by their parent class to suit their specific needs . This capability aids in enhancing the flexibility and scalability of code. Additionally, inheritance supports code reusability, enabling developers to extend existing class functionalities without duplicating code, thereby reducing maintenance effort and potential errors .

Multilevel inheritance in Java is illustrated when a class derives from another derived class, creating a hierarchy of inheritance. An example is when the "BabyDog" class extends "Dog", which extends "Animal" . This allows "BabyDog" to inherit methods like "eat()" from "Animal" and "bark()" from "Dog", promoting reusability and extensibility of code. Advantages include creating a clear hierarchy that allows layered extension of functionality. However, it can also lead to increased complexity, as changes in higher-level classes can impact many subclasses, potentially causing maintenance challenges and unintended side-effects .

Hybrid inheritance in Java is a combination of two or more types of inheritance, such as single, multiple, or multilevel inheritance, which is intended to modularize the code into well-defined classes . While Java does not support hybrid inheritance directly, it can be achieved through interfaces, allowing classes to implement multiple inheritances by using interface hierarchies to mix behaviors from different sources. This is beneficial for modular code structures and increased reusability. However, limitations include potential complexities in managing multiple interfaces and resolving method conflicts without direct support for true multiple class inheritance. It requires careful design to avoid issues like the diamond problem and to maintain a clear and understandable inheritance hierarchy .

You might also like