Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can interface achieve 100% abstraction in Java?

Tags:

java

oop

I have this conceptual query. We say Interface is used to achieve 100% abstraction i.e. hide all the implementation.

But in Interface, all the methods are declared abstract. There is no implementation.

And when the other class implements the same interface then there is no more abstraction as the implementation is defined in the class which implements it.

Please throw some light on it.

like image 203
Adnan Avatar asked Oct 29 '25 00:10

Adnan


2 Answers

You have a misconception about the abstraction interfaces provide.

1. What is an interface?
An interface is a type ob object containing only (public) method signatures (Can vary from language to language). It provides no implementation (function body) of those methods*. It can be seen as a kind of contract an implementing class has to fullfil.

* Many languages allow the user to supply a default implementation in interfaces

2. What kind of abstraction can be achieved by using interfaces?

Created with 'Violet UML Editor' (Created with 'Violet UML Editor')

In this structure the class User only knows that the objects in the objects-array have a method with the signature void Display(). How this method is actually implemented is unknown to User.

The abstraction happening is depicted by the red line. This is the only (pretty powerful) abstraction achieved by interfaces.

The implementation details of the various variants of void Display() are hidden from User. It can just call IDisplayable.Display() and through polymorphism the correct method gets called.

like image 105
LukeG Avatar answered Oct 31 '25 13:10

LukeG


I would like to explain the difference in non programming language.

Assume that you have TV and a Remote. By Remote, you can operate with TV.

Remote had On and Off buttons. When you click on On button, TV will switch on. But you don't know internals of On button implementation . Same is the case with Off button, which switches off TV.

Now Remote is an interface and TV is an implementation object. Map same concepts in java programming language and you will get more clarity.

Remote is interface with On and Off methods. TV implements Remote interface.

Abstraction is hiding details and TV has achieved it. Even in absence of Remote interface, TV can have On and Off buttons and hides the details.

Interface with abstract methods is not necessary to define abstraction. But interface is pure abstract and hides the details of implementation. It exposes contract by hiding internal implementation of implementor.

Have a look at related question

Abstraction VS Information Hiding VS Encapsulation

like image 45
Ravindra babu Avatar answered Oct 31 '25 15:10

Ravindra babu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!