Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Java Inheritance


Java Inheritance (Subclass and Superclass)

In Java, inheritance is a fundamental feature of object-oriented programming (OOP) that allows one class to inherit the properties and behaviors (methods and fields) of another class. This promotes code reuse and enables the creation of hierarchical relationships between classes. Here's an overview of Java inheritance:

Superclass and Subclass:

Syntax for Inheritance:

In Java, inheritance is declared using the extends keyword.

        class Superclass {
            // Superclass members
        }
        
        class Subclass extends Superclass {
            // Subclass members
        }
      

Example of Inheritance:

        class Animal {
            void eat() {
                System.out.println("Animal is eating");
            }
        }
        
        class Dog extends Animal {
            void bark() {
                System.out.println("Dog is barking");
            }
        }
        
        public class Main {
            public static void main(String[] args) {
                Dog dog = new Dog();
                dog.eat();  // Output: Animal is eating
                dog.bark(); // Output: Dog is barking
            }
        }
      

Types of Inheritance:

  1. Single Inheritance: A subclass inherits from only one superclass.
  2. Multilevel Inheritance: A subclass is also a superclass for another subclass.
  3. Hierarchical Inheritance: Multiple subclasses inherit from a single superclass.
  4. Multiple Inheritance (not supported in Java): A subclass inherits from multiple superclasses. Java does not support this directly to avoid ambiguity, but it supports interface implementation to achieve a similar effect.

Access Modifiers in Inheritance:

Method Overriding:

Summary:



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java