Object-oriented programming (OOP) principles such as encapsulation, inheritance, and polymorphism are important concepts that are widely used in software development to create maintainable and scalable systems.
- Encapsulation: Encapsulation is the mechanism of hiding the implementation details of an object and exposing only the necessary information to the outside world. It provides a layer of abstraction and helps to separate the implementation from the interface. This makes the code easier to maintain and less prone to bugs as changes in the implementation do not affect the interface.
Examples of Encapsulation in Java:
class BankAccount {
private:
int accountNumber;
double balance;
public:
BankAccount(int accountNumber, double balance) {
this->accountNumber = accountNumber;
this->balance = balance;
}
int getAccountNumber() {
return accountNumber;
}
double getBalance() {
return balance;
}
};
Examples of Encapsulation in Python:
class BankAccount:
def init(self, account_number, balance):
self.__account_number = account_number
self.__balance = balance
def get_account_number(self):
return self.__account_number
def get_balance(self):
return self.__balance
Examples of Encapsulation in C++:
class BankAccount {
private:
int accountNumber;
double balance;
public:
BankAccount(int accountNumber, double balance) {
this->accountNumber = accountNumber;
this->balance = balance;
}
int getAccountNumber() {
return accountNumber;
}
double getBalance() {
return balance;
}
};
- Inheritance: Inheritance is a mechanism where an object can inherit properties and behaviors from its parent class. This allows code reuse and makes it easier to maintain and scale the system.
Examples of Inheritance in Java:
class BankAccount {
private int accountNumber;
private double balance;
public BankAccount(int accountNumber, double balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
public int getAccountNumber() {
return accountNumber;
}
public double getBalance() {
return balance;
}
}
class SavingsAccount extends BankAccount {
private double interestRate;
public SavingsAccount(int accountNumber, double balance, double interestRate) {
super(accountNumber, balance);
this.interestRate = interestRate;
}
public double getInterestRate() {
return interestRate;
}
}
Examples of Inheritance in Python:
class BankAccount {
private int accountNumber;
private double balance;
public BankAccount(int accountNumber, double balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
public int getAccountNumber() {
return accountNumber;
}
public double getBalance() {
return balance;
}
}
class SavingsAccount extends BankAccount {
private double interestRate;
public SavingsAccount(int accountNumber, double balance, double interestRate) {
super(accountNumber, balance);
this.interestRate = interestRate;
}
public double getInterestRate() {
return interestRate;
}
}