Abstraction in Java
Abstraction in Java
Abstraction is a powerful tool that allows us to hide unnecessary details and only
show the needed information. This makes our code more readable, maintainable,
and reusable.
Data Abstraction may also be defined as the process of identifying only the
required characteristics of an object ignoring the irrelevant details. The properties
and behaviors of an object differentiate it from other objects of similar type and
also help in classifying/grouping the objects.
There are situations in which we will want to define a superclass that declares
the structure of a given abstraction without providing a complete implementation
of every method. Sometimes we will want to create a superclass that only defines
a generalization form that will be shared by all of its subclasses, leaving it to each
subclass to fill in the details.
Abstract classes
Abstract classes are classes that cannot be instantiated directly. They must be
extended by other classes, which are called concrete classes. Concrete classes
implement the abstract methods of the abstract class.
Interfaces
Interfaces are similar to abstract classes, but they have one key difference:
interfaces cannot have any concrete methods. They can only have abstract
methods. Concrete classes must implement all of the abstract methods of the
interfaces they implement.
Example:
Java
abstract class Animal {
abstract void makeSound();
}
In this example, the Animal class is an abstract class. It has one abstract
method, makeSound(). The Dog and Cat classes are concrete classes that extend
the Animal class and implement the makeSound() method.
To use the Animal class, we can create a list of animals and add Dog and Cat
objects to it. We can then iterate over the list and call the makeSound() method
on each animal.
Java
List<Animal> animals = new ArrayList<>();
animals.add(new Dog());
animals.add(new Cat());
Output:
Woof!
Meow!
Benefits of abstraction
Abstraction is used in many parts of the Java standard library. For example:
● The java.io package contains abstract classes and interfaces for reading
and writing data. This allows us to write code that is independent of the
specific underlying I/O device.
● The java.util package contains abstract classes and interfaces for
collections, such as lists, sets, and maps. This allows us to write code that
is independent of the specific implementation of the collection.
● The java.net package contains abstract classes and interfaces for
networking. This allows us to write code that is independent of the specific
underlying network protocol.
Conclusion