Inheritance

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows you to create new classes (derived classes or subclasses) based on existing classes (base classes or superclasses). In Java, inheritance is achieved using the `extends` keyword.

With inheritance, the derived class inherits the properties and methods of the base class, allowing for code reuse and creating an "is-a" relationship between the classes. The derived class can also add its own properties and methods or override the ones inherited from the base class.

Here's an example to illustrate inheritance in Java:





In the above code, we have a base class `Animal` with a private `name` variable and a method `eat()`. The derived class `Dog` extends the `Animal` class using the `extends` keyword. It has an additional method `bark()`.

Now, let's create objects and demonstrate inheritance:



In this code snippet, we create an `Animal` object and a `Dog` object. The `Animal` object can only access the properties and methods defined in the `Animal` class. The `Dog` object, being a subclass of `Animal`, inherits the `name` variable and the `eat()` method from the `Animal` class. It also has access to its own method `bark()`.

The `super(name)` statement in the `Dog` class constructor is used to invoke the base class constructor and provide the `name` argument.

Inheritance allows for code reuse, as the derived class can leverage the existing functionality of the base class. It promotes modularity and abstraction by organizing classes into a hierarchy based on their relationships.

Post a Comment

Previous Post Next Post