Subclass and Superclass in Java

In Java, a subclass is a class that inherits from a superclass. The subclass is able to access and reuse the fields and methods of the superclass, and can also add new fields and methods of its own. This is a powerful feature of object-oriented programming, as it allows developers to create hierarchical relationships between classes and build upon existing functionality.

To create a subclass in Java, we use the extends keyword, followed by the name of the superclass. For example:

public class Dog extends Animal {
  // fields and methods for Dog class go here
}

In this example, the Dog class is a subclass of the Animal class. The Dog class has access to all of the fields and methods of the Animal class, as well as any fields and methods that it defines itself.

It’s important to note that the subclass is a more specific type of the superclass. In other words, a Dog is an Animal, but an Animal is not necessarily a Dog. This is known as an “is-a” relationship.

One common use case for subclassing is to override the methods of the superclass. For example, we might want to define a new behavior for the eat() method for the Dog class, but keep the same behavior for other subclasses of Animal. To do this, we can use the @Override annotation and provide a new implementation of the method in the subclass:

public class Dog extends Animal {
  @Override
  public void eat() {
    // new implementation of eat() method for Dog class
  }
}

Another way to use subclassing is to create a subclass that adds new functionality to the superclass. For example, we might want to create a subclass of Animal called FlyingAnimal, which adds a new fly() method to the Animal class. To do this, we can define the fly() method in the FlyingAnimal subclass:

public class FlyingAnimal extends Animal {
  public void fly() {
    // implementation of fly() method goes here
  }
}

In summary, subclassing is a way to create a new class that is based on an existing class, and to add or modify the functionality of that existing class. It allows developers to build upon existing code and create more specialized classes that can be used in a variety of different contexts.


Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments