Saturday, January 4, 2025
HomeComputer ScienceDifference Between Abstract Class and Interface in Java

Difference Between Abstract Class and Interface in Java

 

In Java, Abstract Classes and Interfaces are both used to define abstract types that specify methods to be implemented by derived classes. However, they have key differences in functionality, use cases, and structure:

Abstract Class

1. Definition: A class that cannot be instantiated on its own and may contain both abstract methods (without implementation) and concrete methods (with implementation).
2. Purpose: Represents an “is-a” relationship. Used to provide a base class with default behavior.
3. Members: Can have:
– Abstract methods.
– Concrete methods.
– Instance variables (can be final or mutable).
– Static methods and blocks.
– Constructors (to initialize fields or perform setup).
4. Inheritance: Supports **single inheritance*. A subclass can extend only one abstract class.
5. Access Modifiers: Methods and variables can have any access modifier (public, protected, private, or package-private).
6. Performance: Slightly faster because it is closer to the hardware and less abstract than interfaces.

See also  Reference Data Types in Java

*Example*:
java
abstract class Animal {
String name;

Animal(String name) {
this.name = name;
}

abstract void makeSound(); // Abstract method

void eat() { // Concrete method
System.out.println(name + ” is eating.”);
}
}

Interface
1. Definition: A completely abstract type that defines a contract for classes to implement. It contains abstract methods by default.
2. Purpose: Represents a “can-do” or “has-a” relationship (e.g., a class “can-do” behavior specified by an interface).
3. Members: Can have:
– Abstract methods (implicitly public and abstract).
– Default methods (introduced in Java 8) with implementation.
– Static methods (introduced in Java 8).
– Constants (implicitly public, static, and final).
4. Inheritance: Supports **multiple inheritance*. A class can implement multiple interfaces.
5. Access Modifiers: Methods are implicitly public. Variables are implicitly public static final.
6. Performance: May have a slight performance overhead due to dynamic method dispatch for interface methods.

See also  How is Computer Science as a degree in top universities?

Example:
java
interface Animal {
void makeSound(); // Abstract method

default void eat() { // Default method with implementation
System.out.println(“This animal is eating.”);
}
}

RELATED ARTICLES

Leave a Reply

- Advertisment -

Most Popular

Recent Comments