Abstraction
Abstraction
➢ In java, abstraction is achieved by interfaces and abstract classes. We can achieve 100%
abstraction using interfaces.
Interfaces in Java - Like a class, an interface can have methods and variables, but the methods
declared in an interface are by default abstract (only method signature, no body).
➢ Interfaces specify what a class must do and not how. It is the blueprint of the class.
➢ An Interface is about capabilities. So it specifies a set of methods that the class has to
implement.
➢ If a class implements an interface and does not provide method bodies for all functions
specified in the interface, then the class must be declared abstract.
➢ A Java library example is, Comparator Interface.
➢ To declare an interface, use interface keyword.
➢ To implement interface use implements keyword.
➢ All the methods are public and abstract. And all the fields are public, static, and final.
2. Static methods: Another feature is that we can now define static methods in interfaces which can
be called independently without an object. Note: these methods are not inherited.
➢ Example of static methods in Interface
// An example to show that interfaces can have methods from JDK 1.8 onwards
interface In1 {
final int a = 10;
static void display() {
System.out.println("hello");
}
}
class TestClass implements In1 {
public static void main (String[] args) {
In1.display(); // Calling with Interface’s name
}
}
Output:
hello
ABSTRACTION ENCAPSULATION
1. It is the process or method of gaining the 1. It is the process or method to contain the
information. information.
2. Problems are solved at the design or
2. Problems are solved at the implementation level.
interface level.
3. It is a method to hide the data in a single entity or
3. It is the method of hiding the unwanted
unit along with a method to protect information from
information.
outside.
4. We can implement abstraction using 4. It can be implemented using by access modifier i.e.
abstract class and interfaces. private, protected and public.
5. Implementation complexities are hidden 5. The data is hidden using methods of getters and
using abstract classes and interfaces. setters.
6. The objects that help to perform abstraction 6. Whereas the objects that result in encapsulation need
are encapsulated. not be abstracted.
Advantages of Abstraction
➢ It reduces the complexity of viewing the things.
➢ Avoids code duplication and increases reusability.
➢ Helps to increase security of an application or program as only relevant details are provided the
user.