Object-Oriented Programming Fundamentals
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects" which can contain data and code. The main principles of OOP are:
1. Encapsulation:
Bundling of data and the methods that operate on that data within a single unit (class). It restricts direct access to some of an object's components, which is a means of preventing accidental interference and misuse of the methods and data.
public class BankAccount {
private double balance; // private - encapsulated
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
public double getBalance() {
return balance;
}
}
2. Inheritance:
A mechanism where you can derive a class from another class for a hierarchy of classes that share a set of attributes and methods.
public class Animal {
public void eat() {
System.out.println("This animal eats food.");
}
}
public class Dog extends Animal {
public void bark() {
System.out.println("The dog barks.");
}
}
3. Polymorphism:
The provision of a single interface to entities of different types or the use of a single symbol to represent multiple different types.
public class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
}
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("The dog barks");
}
}
public class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("The cat meows");
}
}
// Usage:
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.makeSound(); // Outputs: The dog barks
myCat.makeSound(); // Outputs: The cat meows
These principles form the core of OOP and help in creating more organized, flexible, and maintainable code.
Try it Yourself
Create a simple class hierarchy demonstrating inheritance and polymorphism. For example, create a Shape class with subclasses like Circle and Rectangle. Include a method to calculate area in each class. Use the compiler to test your implementation.