Definition
Object-Oriented Programming (OOP) in Java is a programming paradigm based on the concept of "objects," which encapsulate data and behavior. The main principles of OOP are:
- Encapsulation: Bundling data (fields) and methods (functions) that operate on the data into a single unit (class), restricting direct access to some components.
- Inheritance: Mechanism by which one class (child/subclass) acquires the properties and behaviors of another class (parent/superclass).
- Polymorphism: Ability of different classes to respond to the same method call in different ways.
- Abstraction: Hiding complex implementation details and showing only the necessary features of an object.
Worked Example
Problem:
Suppose you want to model animals in Java using OOP principles.
Step 1: Abstraction and Encapsulation
Define an abstract class Animal:
``java
abstract class Animal {
private String name; // Encapsulation
public Animal(String name) {
this.name = name;
}
public String getName() {
return name;
}
public abstract void makeSound(); // Abstraction
}
`
Step 2: Inheritance
Create subclasses that inherit from Animal:
`java
class Dog extends Animal {
public Dog(String name) {
super(name);
}
public void makeSound() {
System.out.println("Woof!");
}
}
class Cat extends Animal {
public Cat(String name) {
super(name);
}
public void makeSound() {
System.out.println("Meow!");
}
}
`
Step 3: Polymorphism
Use polymorphism to call methods:
`java
Animal myDog = new Dog("Buddy");
Animal myCat = new Cat("Whiskers");
myDog.makeSound(); // Output: Woof!
myCat.makeSound(); // Output: Meow!
``
Takeaways
- OOP in Java is built on encapsulation, inheritance, polymorphism, and abstraction.
- These principles help organize code, promote reuse, and simplify maintenance.
- Using OOP, you can model real-world entities and relationships more naturally in code.