Four Pillars of OOP in Java
1. Encapsulation:
Encapsulation is the bundling of data (attributes) and methods (functions) that operate on that data
into a single unit, typically a class. It restricts direct access to some of the object's components.
Example:
```java
class Person {
private String name; // private variable
// Getter method
public String getName() {
return name;
// Setter method
public void setName(String name) {
this.name = name;
```
2. Abstraction:
Abstraction is the concept of hiding complex implementation details and showing only the essential
features of an object. It allows focusing on what an object does instead of how it does it.
Example:
```java
abstract class Animal {
abstract void sound(); // Abstract method
class Dog extends Animal {
void sound() {
System.out.println("Bark");
```
3. Inheritance:
Inheritance allows one class (child class) to inherit fields and methods from another class (parent
class). This promotes code reusability and establishes a hierarchy.
Example:
```java
class Animal {
void eat() {
System.out.println("Eating");
class Dog extends Animal {
void bark() {
System.out.println("Barking");
}
```
4. Polymorphism:
Polymorphism allows methods to do different things based on the object that it is acting upon,
enabling a single interface to control access to different implementations.
Example:
Method Overloading:
```java
class MathOperation {
int add(int a, int b) {
return a + b;
double add(double a, double b) {
return a + b;
```
Method Overriding:
```java
class Animal {
void sound() {
System.out.println("Animal sound");
class Dog extends Animal {
void sound() {
System.out.println("Bark");
```