What is Abstraction in Java?

What is Abstraction in Object Oriented Programming?

Abstraction in java is used to hide the complexity of a system by exposing the method signature of the system but concealing its implementation. Java implements abstraction using interface and abstract class and so it would be easier to explain abstraction by explaining what interfaces and abstract classes do.

What is an interface in java

An interface in java allows declaring methods without providing implemenation for them. Interface is like a class (type) but where the methods do not have any implemenation (reference type). It is the job of the class that implements the interface to provide the implementation of all the methods. Note that there is no concept of “creating an instance” of an interface, since interface only defines an empty skeleton of methods and not the actual implementation. We will have a separate tutorial for interfaces later on. For now here’s a sample interface

public interface IMathematician {
	public void addition();
}

Observe that addition does not have a method body since its abstract.

What is an abstract class in Java

An abstract class has a mix of fully implemented and abstract methods. Abstract methods are ones that do not have any method body and the derived class need to provide one. Abstract classes cannot be instantiated and must be extended to be used. We will look into abstract classes in details in a subsequent tutorial. For now, we look at an example of an abstract class.

public abstract class AbsMathematician {
	public abstract double addition();
	public double subtraction(double a, double b) {
		return a - b;
	}
}

In the abstract class above, the abstract methods have the keyword abstract in them. the method addition is abstract whereas the method subtraction has an implementation.

Abstraction in Java

Abstraction in java be defined as the use of interface and abstract class to provide method definitions that a client can code to but where the actual implementation is provided by subclasses that extend the abstract class or implement the interface. Abstraction is quite a useful concept since it allows the programmers to do the following:

  • Allow development of multiple systems simultaneously since one system only has to know the interface of the other. So we develop the interfaces first and then add implementation later on.
  • Allow multiple implementations of a single interface. So if there is a method that says getCapital(), we can implement the method differently for each country but the client always has to call the getCapital() method. (We will see how that works in a later tutorial)

Leave a Reply

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