Abstraction and Interface in Java
Abstraction in Java:
1. Definition: Abstraction is a concept that hides the implementation details and shows only the
essential features of an object.
2. Types of Abstraction:
a) Abstract classes: Classes that cannot be instantiated and may contain abstract methods
(methods without body).
b) Interfaces: A collection of abstract methods (without implementation), which can be
implemented by a class.
3. Benefits of Abstraction:
- Reduces complexity.
- Improves maintainability.
- Focuses on relevant data and hides irrelevant details.
4. Abstract Methods:
- Methods that are declared without an implementation and must be implemented by subclasses.
- Example: `abstract void display();`
Interface in Java:
1. Definition: An interface is a reference type, similar to a class, that can contain only constants,
method signatures, default methods, static methods, and nested types.
2. Characteristics of Interfaces:
- Can only contain abstract methods (before Java 8).
- Can have default and static methods (since Java 8).
- A class that implements an interface must provide an implementation for all the methods
declared in the interface.
3. Advantages of Interfaces:
- Provides a way to achieve abstraction.
- Allows multiple inheritance (since Java allows a class to implement multiple interfaces).
- Defines a contract that must be followed by implementing classes.
4. Example of Interface:
interface Animal {
void sound();
void move();
class Dog implements Animal {
public void sound() {
[Link]("Bark");
public void move() {
[Link]("Walks on four legs");