Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Full abstraction in java without interfaces

I know that we can achieve 100% abstraction in java with interfaces and partial abstraction with abstract classes.

In interview, interviewer asked me to tell any other way to achieve 100% abstraction except interfaces. Is there any other way?

like image 328
abdul rafay Avatar asked Jan 21 '17 11:01

abdul rafay


People also ask

Is 100% abstraction possible?

In java, abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction using interfaces. Abstract classes and Abstract methods : An abstract class is a class that is declared with an abstract keyword.

Why we Cannot use 100% abstraction in Java?

We cannot create object of abstract class. It is used to achieve abstraction but it does not provide 100% abstraction because it can have concrete methods. An abstract class must be declared with an abstract keyword. It can have abstract and non-abstract methods.

Can we achieve 100% abstraction using abstract class?

Note: Using an abstract class, we can achieve 0-100% abstraction. Remember that, we cannot instantiate (create an object) an abstract class. An abstract class contains abstract methods as well as concrete methods.

Which of the following provides 100% abstraction?

We say Interface is used to achieve 100% abstraction i.e. hide all the implementation.


3 Answers

Use abstract classes that don't have implemented methods. These pure abstract classes like the interfaces has zero implementation.

If you want to learn about pure abstract classes and why they can be used instead of interfaces, you could read pure abstract class and interface.

like image 151
Roman C Avatar answered Oct 11 '22 01:10

Roman C


One could use pure abstract classes with abstract methods only (no fields, no concrete methods).

Edit: Note that starting with the addition of default methods in Java 8, interfaces are no longer necessarily 100% abstract.

In the real world, abstract classes without fields (avoiding state distributed across the hierarchy) are probably more common than pure abstract classes.

like image 41
Stefan Haustein Avatar answered Oct 11 '22 01:10

Stefan Haustein


You have already got your answer i guess as mentioned by Stefan. However, I would like to add that the intention behind creation of abstract classes is to protect the developer to write the same methods for different classes and increase re-usability.

like image 41
Rishav Mishra Avatar answered Oct 11 '22 03:10

Rishav Mishra