Understanding OOP Concepts: Abstraction & Interface

Last modified on February 22, 2020 1 min read

In this topic, I’m going to explain the Abstraction & Interface. Let’s get started.

Table of Contents

  1. Abstraction
  2. Interface

Abstraction

Abstraction is the process of hiding the implementation details and showing only the functionalities to the user. A class that is declared using abstract keyword is known as abstract class.

Let’s know some important info about Abstraction:

  • The abstract keyword is a non-access modifier.
  • Unable to create an object from the abstract class. To access the abstract class, it must be inherited from another class.
  • Abstract methods don’t have body. The body is provided by the child class.
  • Abstract class contains abstract and non-abstract methods.

An example:

abstract class Animal {
  public abstract void sound(); // abstract method
  public void sleep() { // non-abstract method
    System.out.println("Zzz");
  }
}

So, we’re unable to create object like this:

Animal animalObject = new Animal(); // will dislay an error

We’ve to extend from another class and then we’ll able to create object.

// subclass
class Dog extends Animal {
  public void sound() {
    System.out.println("Woof");
  }
}

// create Dog object from another class
class AnotherClass {
  public static void main(String[] args) {
    Dog dog = new Dog();
    dog.sound();
    dog.sleep();
  }
}

Interface

The interface is a collection of abstract methods. It’s like a class. We can say interface is the 100% abstract class.

To use interface in a class, we’ve to use the implements keyword instead of  extends keyword.

Have a look at the example:

interface Animal {
    String info = "Interface class"; // public, static and final

    void sound(); // public and abstract
    void sleep(); // public and abstract
}
// subclass
class Dog implements Animal {
  public void sound() {
    System.out.println("Woof");
  }
  public void sleep() {
    System.out.println("Zzz");
  }
}

// create Dog object from another class
class AnotherClass {
  public static void main(String[] args) {
    Dog dog = new Dog();
    dog.sound();
    dog.sleep();
    System.out.println(info);
  }
}

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

Your email address will not be published. Required fields are marked *