Inheritance, Abstract Class and Interface in Java

Why is Technical Debt Becoming Increasingly Important
[FRS-456] FusionReactor 8.x Release Notes

Inheritance, Abstract Class, and Interface in Java

Inheritance, Abstract Class and Interface in Java: An Overview

Java is an object-oriented programming language that provides several mechanisms to create new classes based on existing classes. One of these mechanisms is inheritance, which allows a class to inherit properties and behaviors from another class. Another mechanism is the abstract class, which is a class that can’t be instantiated and is meant to be extended by other classes. Finally, Java also provides interfaces that declare a set of behaviors a class can implement.

This article will discuss inheritance, abstract class, and interface in Java and how they can be used to build organized and maintainable code. We will also look at how FusionReactor APM can help monitor the performance of applications that use these concepts.

There are four main pillars of OOPS, and they are:

  1. Inheritance
  2. Abstraction
  3. Encapsulation
  4. Polymorphism

How inheritance, abstract class, and interface can be used in Java:

interface Flyable {
void fly();
}
abstract class Animal {
String name;
Animal(String name) {
this.name = name;
}
abstract void makeSound();
}
class Bird extends Animal implements Flyable {
Bird(String name) {
super(name);
}
@Override
void makeSound() {
System.out.println(name + " chirps.");
}
@Override
public void fly() {
System.out.println(name + " is flying.");
}
}
public class Main {
public static void main(String[] args) {
Bird bird = new Bird("Parrot");
bird.makeSound();
bird.fly();
}
}

In this example, the interface Flyable declares the behavior of flying. The abstract class Animal defines a common base class for all animals and provides the abstract method makeSound. The class Bird extends the Animal class and implements the Flyable interface, providing concrete implementations for both makeSound and fly.

When this code is executed, the output will be:

Parrot chirps.
Parrot is flying.

This example demonstrates how inheritance, abstract class, and interface can be used together to create organized and flexible Java code.

An additional pillar in OOPS is the concept of multiple inheritances. C++ only supports this concept, and it has pitfalls while writing complex code; hence the other languages which originated much later to C++ dropped this idea of multiple inheritances rather than modified it to be adopted differently. In Java, it is supported through the concept of interfaces.

Inheritance

In the biological world, all living organisms inherit some or all the properties of their parents. An object-Oriented Programming paradigm is based on this real-world philosophy. A child will derive some or all the features of their parents. In Java, ‘extends’ keyword is used to show inheritance.

Let us try to understand with the example of class Animal and class Cat. In this case, Animal class can be considered as a parent class, whereas class Cat can be considered as a child class. A class in Java is the blueprint for creating objects. An object has properties and states. Properties are denoted using methods, while states are denoted using variables. When we design classes for our java program, we can design the parent class methods and states.

Animal
-sound: String
-sleep: String
-legs: int
-diet: String 
+getSound(): String
+getSleep(): String
+getLegs(): int
+getDiet(): String
Cat
-type : String
-size : String
-breed: String
+getType(): String
+getsize(): String
+getbreed(): String

When we design our Cat class, we need not rewrite all the code for the cat class from scratch and can reuse the code from the animal class. The cat class can be designed to add further some more properties and can reuse the properties of the animal class. Here is the sample code for inheritance:

  private String sound;
  private String sleep;
  private String legs;
  private String diet; // Animal attribute
  public String getSound() { // Animal method
      //implementation of getSound() method here
  }
  public String getSleep() {
      //implementation of getSleep() method here
  }
  public String getLegs() {
      //implementation of getLegs() method here
  }
  public String getDiet() {
      //implementation of getDiet() method here
  }
}
class Cat extends Animal { //Cat class inherits methods of Animal
  private String type;	// Cat attribute
  private String size;
  private String breed;

  public String getType() {
      //implementation of getType() method here
  }
  public String getSize() {
      //implementation of getSize() method here
  }
  public String getBreed() {
      //implementation of getBreed() method here
  }

  public static void main(String[] args) {
   Cat myCat= new Cat();
   myCat.getSleep();
   myCat.getLegs();
   myCat.getBreed();	
  }
}

Abstraction

The OOPS provides the benefit of hiding non-essential details from the end-user by providing an abstraction. A driver of the car need not necessarily know under the hood implementation of the gearbox, steering mechanism, etc. He/she is shown only the relevant and essential details which he/she wants to know. For example, a driver would be more interested in the clutch, gear, brake, accelerator, dashboard, horn, windshield, side mirror, Air conditioning working, but would not be interested in their implementation. In Java, abstraction can be implemented by using:

a)     Abstract Class

b)     Abstract method

c)     Interfaces

The keyword ‘abstract’ is a non-access modifier and is used for both abstract classes and abstract methods to achieve abstraction. Interface itself helps in achieving the abstraction.

Abstract Class

A java class is declared abstract using the keyword ‘abstract’ and can contain both abstract and non-abstract methods. It cannot be instantiated, or its objects can’t be created. A class inheriting the abstract class has to provide the implementation for the abstract methods declared in the abstract class. An abstract class can contain constructors, static methods, and final methods as well.

Abstract Method

Abstract keyword is used to declare a method abstract, and the method cannot have an implementation in the class where it is declared. The inheriting class has to provide the implementation for that abstract method.

The below sample code will show the example of an abstract class and abstract method. Notice the subclass has to provide the implementation for the abstract method.

// Abstract class abstract class Animal { // Abstract method public abstract void eyeColor(); // Regular method public void sound() { System.out.println("purr"); } } // Subclass (inherit from Animal) class Pig extends Animal { public void favoriteFood() { // The body of favoriteFood() is provided here System.out.println("Hay Stack"); } public void eyeColor() { //implementation of parent abstract method is given here System.out.println(“Eye color is black”); } } class MyMainClass { public static void main(String[] args) { Pig pig = new Pig(); // Create a Truck object pig.eyeColor(); pig.favoriteFood(); } }

Interface

Before diving deeper into the concepts of an Interface implementation, we have first to understand the concept of multiple inheritances used by C++. Before Java came into the world, several programming languages were trying to solve the complexity of the code generated using multiple inheritance. It was C++, where it was widely adopted. No doubt, C++ brought Object-Oriented Programming into the world but also introduced some of the complex problems due to the concept of multiple inheritances.

What is Multiple Inheritance?

According to multiple inheritance, a child can have multiple parents. This means that a child can implement the properties of several parents at the same time. This created ambiguity for similar types of properties implemented by various parents. It added to the complexity of the code and introduced bugs in the developed code.

To tackle the problem that was created by multiple inheritance, several ideas were put forward and implemented. Java used interfaces to provide the features used by multiple inheritance.

Interfaces can also be considered an abstract class which group similar methods without any implementation. To use interface in the java code, ‘implements’ keyword is used. A class can implement several interfaces, thus providing similar features that are provided by multiple inheritance. The below example describes an interface and its implementation.

// Interface interface Animal { public void sound(); // interface method public void sleep(); // interface method } interface Breed { public void domesticBreed(); } // Dog "implements" the Animal interface class Dog implements Animal, Breed { public void sound() { // The implementation of sound() is provided here System.out.println("The dog says: woof woof"); } public void sleep() { // The body of sleep() is provided here System.out.println("Zzz"); } public void domesticBreed(){ //implementation of domesticBreed() method System.out.println(“Yes”); } } class MyMainClass { public static void main(String[] args) { Dog dog = new Dog(); // Create a Dog object dog.sound(); dog.sleep(); dog.domesticBreed(); } }

Inheritance, Abstract Class and Interface in Java

Java is an object-oriented programming language, and the above topics form the key pillars of object-oriented programming, or we can also say that Java provides an object-oriented programming paradigm through inheritance, abstraction, and interface.

How FusionReactor APM can help monitor performance

FusionReactor APM (Application Performance Monitoring) is a tool that can help monitor and optimize the performance of Java applications. It provides detailed performance metrics, request tracing, memory usage, and other information to help identify and diagnose performance issues.

If you have a Java application that uses inheritance, abstract class, and interface, FusionReactor APM can provide valuable insights into its performance and help you identify and resolve performance bottlenecks. For example, suppose you have a class that implements multiple interfaces. In that case, FusionReactor APM can help you monitor the performance of each interface and identify which interface is affecting the application’s overall performance. Similarly, if you have a complex inheritance hierarchy, FusionReactor APM can help you visualize the inheritance chain and identify any performance issues in the parent or child.

Conclusion: Inheritance, Abstract Class, and Interface in Java

Inheritance, abstract class, and interface are key concepts in Java that help developers create organized and maintainable code. Inheritance allows a class to inherit properties and behaviors from another class, the abstract class provides a common base class for a group of related classes, and interface defines a set of behaviors that a class can implement. Each concept has its use cases and can be combined to create complex and flexible Java applications.

FusionReactor APM is a tool that can help monitor and optimize the performance of Java applications that use these concepts. It provides detailed performance metrics, request tracing, memory usage, and other information to help identify and diagnose performance issues. By using FusionReactor APM, developers can ensure that their Java applications are running smoothly and efficiently, even as they take advantage of the powerful features offered by inheritance, abstract class, and interface.

Recent Posts