dave
dave

Reputation: 19

How abstract class and interface achieve abstraction in java?

In general, Abstraction is defined as hiding unnecessary information and showing only what's essential to the user. But how does abstract class and interface achieve this?

Upvotes: 0

Views: 1022

Answers (2)

mentallurg
mentallurg

Reputation: 5207

The purpose of abstract classes and interfaces has nothing to do with hiding anything.

Interfaces

You can consider interface as a contract. Compiler makes sure that any non-abstract class that implements this interface does have all the methods declared in the interface. There are no any other limitations on the classes that implement this interface.

Abstract classes

An abstract class defines the most important functionality of the class. It is kind of skeleton. It allows subclasses to provide their own implementations of the abstract methods.

In some cases the purpose is to reuse the common code. If it makes sense in particular case, a default implementation class can be created. But in many cases a default class makes not sense. For instance, in Java there is AbstractCollection. It defines common behaviour of all collection classes. A default collection makes no sense, because some developers may expect that default implementation is a list, the others will expect a set, and smb. will expect that it is non-ordered collection (unlike list) and allows duplicates (unlike set).

In other cases an abstract class may be used to define some core logic that should not be changed in subclasses. Then some methods in the public class can be made final.

If we compare interfaces and abstract classes, we can see interfaces as pure abstraction, where as abstract classes are more specific, they usually do implement some logic.

Upvotes: 2

Louis Wasserman
Louis Wasserman

Reputation: 198211

Typically, the approach is that you only show the user the interface of the object you're passing back to them, instead of the precise class that implements that interface. The interface is the essential implementation, the exact class is unnecessary information.

Upvotes: 2

Related Questions