Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Inheritance Basics → Inheritance

Inheritance Basics


Inheritance in Java is a mechanism where one class acquires, or inherits, the properties (fields) and behaviors (methods) of another class. With the use of inheritance, information is managed in a hierarchical manner. The class which inherits the properties of another class is known as the subclass (or derived class, child class), and the class whose properties are inherited is known as the superclass (or base class, parent class). In simple words, Inheritance is a fundamental concept in Java’s Object-Oriented Programming (OOP). It allows a class to inherit the features (fields and methods) of another class, promoting code reusability and method overriding. Here are some key terminologies used in Java Inheritance: Class: A set of objects sharing common characteristics or behavior. Super Class/Parent Class: The class whose features are inherited. Sub Class/Child Class: The class that inherits from another class. Reusability: The concept of reusing the fields and methods of an existing class when creating a new class. In Java, the extends keyword is used for inheritance. Here’s the syntax:
Extents keyword basic syntax class derived-class extends base-class { // methods and fields }
Here’s an example of inheritance in Java:
Basic example of inheritance in java using extend keyword public class Main { public static void main(String args[]) { Dog d = new Dog(); d.bark();; } } // This is the superclass class Animal { void eat() { System.out.println("eating..."); } } // Dog class inherits Animal class class Dog extends Animal { void bark() { System.out.println("barking..."); } }


barking... eating...
In this example, Dog is a subclass which inherits the Animal superclass. The Dog class can access the eat method of the Animal class due to inheritance. The Dog class also has its own method bark. In the main method, we create an object of the Dog class and call both the bark and eat methods.This demonstrates that the Dog object can use both the methods from its own class and the superclass it extends. This is the basic concept of inheritance in Java. Java supports different types of inheritance, including single inheritance, multilevel inheritance, and hierarchical inheritance. However, multiple inheritance is not supported in Java through class.