(Translated by https://www.hiragana.jp/)
Interfaces and Inheritance in Java - GeeksforGeeks
Open In App

Interfaces and Inheritance in Java

Last Updated : 11 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A class can extend another class and can implement one and more than one Java interface. Also, this topic has a major influence on the concept of Java and Multiple Inheritance.

interface_2  

Note: This Hierarchy will be followed in the same way, we cannot reverse the hierarchy while inheritance in Java. This means that we cannot implement a class from the interface because Interface-to-Class inheritance is not allowed, and it goes against the fundamental principles of class-based inheritance. This will also breach the relationship known as the Is-A relationship, where a subclass is a more specialized version of its superclass.

Example:

Java




// Java program to demonstrate that a class can
// implement multiple interfaces
import java.io.*;
 
interface intfA {
    void m1();
}
 
interface intfB {
    void m2();
}
 
// class implements both interfaces
// and provides implementation to the method.
class sample implements intfA, intfB {
    @Override public void m1()
    {
        System.out.println("Welcome: inside the method m1");
    }
 
    @Override public void m2()
    {
        System.out.println("Welcome: inside the method m2");
    }
}
 
class GFG {
    public static void main(String[] args)
    {
        sample ob1 = new sample();
 
        // calling the method implemented
        // within the class.
        ob1.m1();
        ob1.m2();
    }
}


Output:

Welcome: inside the method m1
Welcome: inside the method m2

Interface inheritance: An Interface can extend another interface. interface_inheritance 

Inheritance is inheriting the properties of the parent class into the child class.

  1. Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object.
  2. The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. 
  3. You can also add new methods and fields in your current class.
  4. Inheritance represents the IS-A relationship which is also known as the parent-child relationship.

Example

Dog IS_A Animal
Car IS_A Vehicle
Employee IS_A Person
Surgeon IS_A Doctor etc.

Below is the implementation of the above method:

Java




// Animal is a Parent class
class Animal {
    public void eat()
    {
        System.out.println("Animal is eating");
    }
}
 
// Here Dog is derived from Animal class
class Dog extends Animal {
    public static void main(String args[])
    {
        // creating object of Dog class
        Dog d = new Dog();
 
        // Now, Dog can access eat() method of Animal class
        d.eat();
    }
}


Output

Animal is eating

Syntax of Java Inheritance

class <Subclass-name> extends <Superclass-name>
{
    //methods and fields
}

Note: The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of “extends” is to increase the functionality.

Example of Java Inheritance

Below is the implementation of Java Inheritance:

Java




// Java Program to demonstrate
// Java Inheritance
 
// Parent Class
class Person1 {
      // Variables
    int id;
    String name;
   
      // Java Methods
    void set_Person(int id, String name)
    {
        try {
            this.id = id;
            this.name = name;
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    void disp_Person()
    {
        System.out.print(id + "\t" + name + "\t");
    }
}
 
// Child Class
class Employee1 extends Person1 {
    int sal;
    String desgn;
    void set_Emp(int id, String name, String desgn, int sal)
    {
        try {
            set_Person(id, name);
            this.desgn = desgn;
            this.sal = sal;
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    void disp_Emp()
    {
        disp_Person();
        System.out.print(desgn + "\t" + sal);
    }
   
      // Main function
    public static void main(String args[])
    {
 
        Employee1 e1 = new Employee1();
        e1.set_Emp(1001, "Manjeet", "AP", 20000);
        e1.disp_Emp();
    }
}


Output

1001    Manjeet    AP    20000

Types of inheritance in Java

  1. Java supports three types of inheritance in Java: single-level, multilevel, and hierarchical inheritance in the case of classes to avoid ambiguity.
  2. In Java programming, multiple and hybrid inheritance is supported through the interface only.

1. Single Inheritance Example

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

Java




// Single-Level inheritance
// Class B ---> Class A, which means that class B is derived from Class A
 
class A {
    int a;
    void set_A(int x) {
      a = x;
    }
}
 
// Class B have access to all public and protected methods and data members of Class A
class B extends A {
    int b, product;
    void set_B(int x) {
      b = x;
    }
    void cal_Product()
    {
        product = a * b;
        System.out.println("Product = " + product);
    }
    public static void main(String[] args)
    {
        B b = new B();
        b.set_A(5);
        b.set_B(5);
        b.cal_Product();
    }
}


Output

Product = 25

2. Multilevel Inheritance Example

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

Below is the implementation of the above method:

Java




// Multilevel inheritance
// Class C ---> Class B ---> Class A
// Class C is derived from Class B which in correspondence derived from Class A
 
class A {
    int a;
    void set_A(int x) {
      a = x;
    }
}
 
// Child of Class A
class B extends A {
    int b;
    void set_B(int x) {
      b = x;
    }
}
 
// Child of Class B but have access to methods of both classes, i.e., Class A and B
class C extends B {
    int c, product;
    void cal_Product()
    {
        product = a * b;
        System.out.println("Product = " + product);
    }
    public static void main(String[] args)
    {
        C c = new C();
          // Class C accesses methods of both class A and B
        c.set_A(5);
        c.set_B(5);
        c.cal_Product();
    }
}


Output

Product = 25

3. Hierarchical Inheritance Example

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

Below is the implementation of the mentioned topic:

Java




// Hierarchical inheritance
// Class C ---> Class A <--- Class B
// Both Class B and C inherits Class A
 
class A {
    int a;
    void set_A(int x) {
          a = x;
          System.out.println("Setting A's value to = " + x);
    }
}
 
// Class B derived from Class A
class B extends A {
    int b;
    void set_B(int x) {
      b = x;
      System.out.println("Setting B's value to = " + b);
    }
}
 
// Class C also derived from Class A
class C extends A {
    int c;
    void set_C(int x) {
      c = x;
      System.out.println("Setting C's value to = " + c);
    }
}
 
public class GFG {
      public static void main(String[] args) {
          C c = new C();
          c.set_C(5);
          c.set_A(50);
           
          B b = new B();
          b.set_B(10);
          b.set_A(15);
    }
}


Output

Setting C's value to = 5
Setting A's value to = 50
Setting B's value to = 10
Setting A's value to = 15

4. Inheritance in Interfaces

Java




// Java program to demonstrate inheritance in
// interfaces.
import java.io.*;
interface intfA {
    void geekName();
}
 
interface intfB extends intfA {
    void geekInstitute();
}
 
// class implements both interfaces and provides
// implementation to the method.
class sample implements intfB {
    @Override public void geekName()
    {
        System.out.println("Rohit");
    }
 
    @Override public void geekInstitute()
    {
        System.out.println("JIIT");
    }
 
    public static void main(String[] args)
    {
        sample ob1 = new sample();
 
        // calling the method implemented
        // within the class.
        ob1.geekName();
        ob1.geekInstitute();
    }
}


Output:

Rohit
JIIT

An interface can also extend multiple interfaces. 

Java




// Java program to demonstrate multiple inheritance
// in interfaces
 
import java.io.*;
 
interface intfA {
    void geekName();
}
 
interface intfB {
    void geekInstitute();
}
 
// always remember that interfaces always extends interface
// but a class always implements a interface
interface intfC extends intfA, intfB {
    void geekBranch();
}
 
// class implements both interfaces and provides
// implementation to the method.
class sample implements intfC {
    public void geekName() { System.out.println("Rohit"); }
 
    public void geekInstitute()
    {
        System.out.println("JIIT");
    }
 
    public void geekBranch() { System.out.println("CSE"); }
 
    public static void main(String[] args)
    {
        sample ob1 = new sample();
 
        // calling the method implemented
        // within the class.
        ob1.geekName();
        ob1.geekInstitute();
        ob1.geekBranch();
    }
}


Output

Rohit
JIIT
CSE


Q. Why Multiple Inheritance is not supported through a class in Java, but it can be possible through the interface?

Multiple Inheritance is not supported by class because of ambiguity. In the case of interface, there is no ambiguity because the implementation of the method(s) is provided by the implementing class up to Java 7. From Java 8, interfaces also have implementations of methods. So if a class implements two or more interfaces having the same method signature with implementation, it is mandated to implement the method in class also.

Refer to Java and Multiple Inheritance for details. 



Previous Article
Next Article

Similar Reads

How to Implement Multiple Inheritance by Using Interfaces in Java?
Multiple Inheritance is a feature of an object-oriented concept, where a class can inherit properties of more than one parent class. The problem occurs when methods with the same signature exist in both the superclasses and subclass. On calling the method, the compiler cannot determine which class method to be called and even on calling which class
2 min read
Generic Constructors and Interfaces in Java
Generics make a class, interface and, method, consider all (reference) types that are given dynamically as parameters. This ensures type safety. Generic class parameters are specified in angle brackets “<>” after the class name as of the instance variable. Generic constructors are the same as generic methods. For generic constructors after th
5 min read
Interfaces and Polymorphism in Java
Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JA is that Java tries to connect every concept in the language to the real world with the help
6 min read
Callback using Interfaces in Java
Callback in C/C++ : The mechanism of calling a function from another function is called “callback”. Memory address of a function is represented as ‘function pointer’ in the languages like C and C++. So, the callback is achieved by passing the pointer of function1() to function2().Callback in Java : But the concept of a callback function does not ex
4 min read
Private Methods in Java 9 Interfaces
Java 9 onwards, you can include private methods in interfaces. Before Java 9 it was not possible. Interfaces till Java 7 In Java SE 7 or earlier versions, an interface can have only two things i.e. Constant variables and Abstract methods. These interface methods MUST be implemented by classes which choose to implement the interface. // Java 7 progr
4 min read
Why Java Interfaces Cannot Have Constructor But Abstract Classes Can Have?
Prerequisite: Interface and Abstract class in Java. A Constructor is a special member function used to initialize the newly created object. It is automatically called when an object of a class is created. Why interfaces can not have the constructor? An Interface is a complete abstraction of class. All data members present in the interface are by de
4 min read
Which Java Types Can Implement Interfaces?
In Java there is no concept of multiple-inheritance, but with the help of interface we can achieve multiple-inheritance. An interface is a named collection of definition. (without implementation) An interface in Java is a special kind of class. Like classes, interface contains methods and members; unlike classes, in interface all members are final
7 min read
Match Lambdas to Interfaces in Java
One of the most popular and important topics is lambda expression in java but before going straight into our discussion, let us have insight into some important things. Starting off with the interfaces in java as interfaces are the reference types that are similar to classes but containing only abstract methods. This is the definition of interface
5 min read
Types of Interfaces in Java
In Java, an interface is a reference type similar to a class that can contain only constants, the method signatures, default methods, and static methods, and its Nested types. In interfaces, method bodies exist only for default methods and static methods. Writing an interface is similar to writing to a standard class. Still, a class describes the a
6 min read
Access modifiers for classes or interfaces in Java
In Java, methods and data members can be encapsulated by the following four access modifiers. The access modifiers are listed according to their restrictiveness order. 1) private (accessible within the class where defined) 2) default or package-private (when no access modifier is specified) 3) protected (accessible only to classes that subclass you
1 min read
Interfaces in Java
An Interface in Java programming language is defined as an abstract type used to specify the behavior of a class. An interface in Java is a blueprint of a behavior. A Java interface contains static constants and abstract methods. What are Interfaces in Java?The interface in Java is a mechanism to achieve abstraction. Traditionally, an interface cou
11 min read
Functional Interfaces in Java
Java has forever remained an Object-Oriented Programming language. By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some of the primitive data types and primitive methods for integrity and simplicity. There are no solely functions present in a
10 min read
Java and Multiple Inheritance
Multiple Inheritance is a feature of an object-oriented concept, where a class can inherit properties of more than one parent class. The problem occurs when there exist methods with the same signature in both the superclasses and subclass. On calling the method, the compiler cannot determine which class method to be called and even on calling which
6 min read
Difference between Inheritance and Composition in Java
Inheritance: 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. In doing this, we can reuse the fields and methods of the existing class without having to write them ourself. A subclass inherits all the members (fields, methods, and nested
3 min read
Difference between Inheritance and Interface in Java
Java is one of the most popular and widely used programming languages. Java has been one of the most popular programming languages for many years. Java is Object Oriented. However, it is not considered as a pure object-oriented as it provides support for primitive data types (like int, char, etc). In this article, we will understand the difference
3 min read
Illustrate Class Loading and Static Blocks in Java Inheritance
Class loading means reading .class file and store corresponding binary data in Method Area. For each .class file, JVM will store corresponding information in Method Area. Now incorporating inheritance in class loading. In java inheritance, JVM will first load and initialize the parent class and then it loads and initialize the child class. Example
3 min read
Inheritance and Constructors in Java
Constructors in Java are used to initialize the values of the attributes of the object serving the goal to bring Java closer to the real world. We already have a default constructor that is called automatically if no constructor is found in the code. But if we make any constructor say parameterized constructor in order to initialize some attributes
3 min read
Comparison of Inheritance in C++ and Java
The purpose of inheritance is the same in C++ and Java. Inheritance is used in both languages for reusing code and/or creating an ‘is-a’ relationship. The following examples will demonstrate the differences between Java and C++ that provide support for inheritance. 1) In Java, all classes inherit from the Object class directly or indirectly. Theref
4 min read
How to Create Interfaces in Android Studio?
Interfaces are a collection of constants, methods(abstract, static, and default), and nested types. All the methods of the interface need to be defined in the class. The interface is like a Class. The interface keyword is used to declare an interface. public interface AdapterCallBackListener { void onRowClick(String searchText); } public interface
4 min read
Access specifier of methods in interfaces
In Java, all methods in an interface are public even if we do not specify public with method names. Also, data fields are public static final even if we do not mention it with fields names. Therefore, data fields must be initialized. Consider the following example, x is by default public static final and foo() is public even if there are no specifi
1 min read
Two interfaces with same methods having same signature but different return types
Java does not support multiple inheritances but we can achieve the effect of multiple inheritances using interfaces. In interfaces, a class can implement more than one interface which can't be done through extends keyword. Please refer Multiple inheritance in java for more. Let's say we have two interfaces with same method name (geek) and different
2 min read
Output of Java program | Set 23 (Inheritance)
Prerequisite: Inheritance in Java 1) What is the output of the following program? Java Code public class A extends B { public static String sing() { return "fa"; } public static void main(String[] args) { A a = new A(); B b = new A(); System.out.println(a.sing() + " " + b.sing()); } } class B { public static String sing() { retu
3 min read
Resolving Conflicts During Multiple Inheritance in Java
A class can implement multiple interfaces in java, but what if the implemented multiple default interfaces have default methods with the same signatures? Then in the implementing class, which of the default implementations would be invoked from the several parent interfaces. Java 8 designers have been thinking about this conflict and have specified
5 min read
Java - Exception Handling With Constructors in Inheritance
Java provides a mechanism to handle exceptions. To learn about exception handling, you can refer to exceptions in java. In this article, we discuss exception handling with constructors when inheritance is involved. In Java, if the constructor of the parent class throws any checked exception, then the child class constructor can throw the same excep
7 min read
What is the Need of Inheritance in Java?
Inheritance, as we have all heard is one of the most important features of Object-Oriented Programming Languages whether it is Java, C++, or any other OOP language. But what is the need for Inheritance? Why is it so an important concept Inheritance can be defined as a mechanism by which one object can acquire all the properties (i.e. data members)
6 min read
Using final with Inheritance in Java
Prerequisite - Overriding in java, Inheritance final is a keyword in java used for restricting some functionalities. We can declare variables, methods, and classes with the final keyword. Using final with inheritance During inheritance, we must declare methods with the final keyword for which we are required to follow the same implementation throug
4 min read
Object Serialization with Inheritance in Java
Prerequisite: Serialization, Inheritance Serialization is a mechanism of converting the state of an object into a byte stream. The byte array can be the class, version, and internal state of the object. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persis
6 min read
Delegation vs Inheritance in Java
Inheritance in Java programming is the process by which one class takes the property of another other class. i.e. the new classes, known as derived or child class, take over the attributes and behavior of the pre-existing classes, which are referred to as base classes or super or parent class.Delegation is simply passing a duty off to someone/somet
3 min read
Why Java doesn't support Multiple Inheritance?
Multiple Inheritance is a feature provided by OOPS, it helps us to create a class that can inherit the properties from more than one parent. Some of the programming languages like C++ can support multiple inheritance but Java can't support multiple inheritance. This design choice is rooted in various reasons including complexity management, ambigui
5 min read
Favoring Composition Over Inheritance In Java With Examples
In object-oriented programming (OOP), choosing between inheritance and composition is crucial for designing flexible and maintainable code. This article explores why you should favor composition over inheritance, with simple explanations and examples. What is Inheritance?Inheritance is when a new class is based on an existing class. The new class (
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg