ByteBrawl - Extending A Class - Extend Classes - Inheritance

Extend Classes - Extending A Class

Inheritance is a fundamental concept in object-oriented programming that allows a new class (called a subclass or derived class) to inherit properties and behaviors from an existing class (called a superclass or base class). This promotes code reuse and establishes a natural hierarchy between classes. We've touched upon many concepts related to inheritance already, such as subclasses, the protected access modifier, and abstract classes and methods. In this section, we'll explore inheritance in more detail.

Extending a Class

To create a subclass that inherits from a superclass, we use the extends keyword. The subclass can then access public and protected members of the superclass, as well as any default members if they are in the same package. A class can only extend 1 superclass. Here's an example:

Animal.java

Main.java

In this example, the Dog class extends the Animal class, inheriting its eat method. The Dog class also has its own method, bark. When we create an instance of Dog, we can call both the inherited eat method and the bark method.