#javaDay19

Опубликовано: 13 Май 2026
на канале: Geeks With Geeks
12
0

Java OOPs - Abstract Classes And Interfaces are essential concepts that facilitate abstraction, polymorphism, and code reusability in Java programming. Both abstract classes and interfaces serve as blueprints for other classes to inherit from or implement, respectively. Let's delve into each of these concepts:

1. **Abstract Classes**:
An abstract class in Java is a class that cannot be instantiated directly and may contain abstract methods.
Abstract methods are declared without a body and must be implemented by concrete subclasses.
Abstract classes can also contain concrete methods with implementations.
They are defined using the `abstract` keyword.

2. **Interfaces**:
An interface in Java is a reference type, similar to a class, that contains only abstract methods, default methods, static methods, and constant fields.
Interfaces provide a contract for classes to implement, defining a set of methods that the implementing class must override.
Multiple interfaces can be implemented by a single class, facilitating multiple inheritance of type.
They are defined using the `interface` keyword.

Key differences between abstract classes and interfaces:
Abstract classes can have constructors, member variables, and concrete methods, whereas interfaces cannot.
A class can extend only one abstract class but can implement multiple interfaces.
Abstract classes are useful when you want to provide a common base implementation, while interfaces are useful for defining contracts or specifying behaviors that classes must implement.

Example of an abstract class:
```java
abstract class Shape {
abstract double area(); // Abstract method

void display() {
System.out.println("This is a shape.");
}
}
```

Example of an interface:
```java
interface Drawable {
void draw(); // Abstract method

default void display() {
System.out.println("This is a drawable object.");
}
}
```