OOP principles in Java Simplified
Encapsulation
bundling of fields and methods into a single unit (class)
basically this is done to allow a restricted access to certain components with use of access modifiers (public, private, protected etc)
In Spring Boot Rest API, encapsulation ensure that data models only expose necessary fields
A User
entity class hide sensitive information like password. Passwords can be hashed and validated internally within the class or service layer without direct exposure.
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = hashPassword(password);
}
private String hashPassword(String password) {
// Hashing logic here
return passwordHash;
}
}
Inheritance
allows a class to inherit fields and methods from another class, promoting code reuse and hierarchy modeling
A BaseEntity
class can include common properties like id
, createdAt
, updatedAt
, which are inherited by other entity classes like Order
and Customer
.
@MappedSuperclass
public class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
// Getters and setters
}
@Entity
public class Customer extends BaseEntity {
private String name;
private String email;
// Additional fields and methods
}
Polymorphism
allows methods to perform different tasks based on the object calling them. It can be achieved via method overriding or overloading.
Different payment methods (CreditCardPayment
, PaypalPayment
) can implement a common PaymentService
interface. The system dynamically determines the appropriate method to invoke.
public interface PaymentService {
void processPayment(double amount);
}
public class CreditCardPayment implements PaymentService {
@Override
public void processPayment(double amount) {
System.out.println("Processing credit card payment of " + amount);
}
}
public class PaypalPayment implements PaymentService {
@Override
public void processPayment(double amount) {
System.out.println("Processing PayPal payment of " + amount);
}
}
Abstraction
hides implementation details and shows only essential features to the user
In API design, abstraction is employed to define service contracts while hiding implementation details.
An abstract NotificationService
can define methods for sending notifications without exposing the underlying implementations (email, SMS, push notifications).
public abstract class NotificationService {
public abstract void sendNotification(String message, String recipient);
}
public class EmailNotificationService extends NotificationService {
@Override
public void sendNotification(String message, String recipient) {
System.out.println("Sending email to " + recipient + ": " + message);
}
}