vault backup: 2025-03-16 18:59:42
This commit is contained in:
@@ -1,8 +1,8 @@
|
||||
# What is an interface in object-oriented programming and how does it differ from a class?
|
||||
# What is an Interface in Object-oriented Programming and how Does it Differ from a Class?
|
||||
|
||||
### **What is an Interface in Object-Oriented Programming?**
|
||||
### **What Is an Interface in Object-Oriented Programming?**
|
||||
|
||||
An **interface** is a contract in object-oriented programming (OOP) that defines a set of methods (and sometimes properties) that a class must implement. It specifies _what_ a class should do, but not _how_ it should do it.
|
||||
An **interface** is a contract in object-oriented programming (OOP) that defines a set of methods (and sometimes properties) that a class must implement. It specifies *what* a class should do, but not *how* it should do it.
|
||||
|
||||
Key characteristics of an interface:
|
||||
|
||||
@@ -12,6 +12,7 @@ Key characteristics of an interface:
|
||||
4. **No State**: Interfaces do not contain instance variables or state but may include constants.
|
||||
|
||||
#### Example in Java:
|
||||
|
||||
```java
|
||||
// Define an interface
|
||||
public interface Animal {
|
||||
@@ -33,7 +34,7 @@ public class Dog implements Animal {
|
||||
}
|
||||
```
|
||||
|
||||
### **What is a Class?**
|
||||
### **What Is a Class?**
|
||||
|
||||
A **class** is a blueprint for creating objects in OOP. It defines the structure (fields or attributes) and behavior (methods) of objects. Unlike interfaces, classes can have implementations, state, and behavior.
|
||||
|
||||
@@ -45,6 +46,7 @@ Key characteristics of a class:
|
||||
4. **Constructors**: Classes can have constructors to initialize objects.
|
||||
|
||||
#### Example in Java:
|
||||
|
||||
```java
|
||||
// Define a class
|
||||
public class Dog {
|
||||
@@ -73,13 +75,14 @@ public class Dog {
|
||||
|**Constructors**|Cannot have constructors.|Can have constructors to initialize objects.|
|
||||
|**Abstract**|Interfaces are entirely abstract (unless extended in modern versions).|Can be abstract or concrete.|
|
||||
|**Default Methods**|Starting from Java 8, interfaces can have default methods (methods with a body).|Classes always support method implementation.|
|
||||
### **When to Use an Interface?**
|
||||
|
||||
### **When To Use an Interface?**
|
||||
|
||||
- **Polymorphism**: When you want different classes to provide their specific implementation of the same behavior.
|
||||
- **Decoupling**: To decouple code by relying on abstractions rather than concrete classes.
|
||||
- **Multiple Inheritance**: When you need a class to inherit behavior from multiple sources.
|
||||
|
||||
### **When to Use a Class?**
|
||||
### **When To Use a Class?**
|
||||
|
||||
- When you need to define an object with both state and behavior.
|
||||
- When you need concrete implementations of methods.
|
||||
|
Reference in New Issue
Block a user