Java OOP Concepts

Object-Oriented Programming (OOP) is a programming paradigm that uses "objects" to represent data and methods. Java is a popular OOP language that emphasizes four key concepts: Encapsulation, Inheritance, Polymorphism, and Abstraction.

Key Points on OOP:

1. Encapsulation

Encapsulation is the bundling of data and methods that operate on that data within one unit, usually a class. It restricts access to some components, which can help prevent accidental modification of data.

Code Example:

Code Example: Encapsulation

public class Person {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Output

(No output for encapsulation example; use getter and setter methods to manipulate data)

2. Inheritance

Inheritance allows a class (child class) to inherit fields and methods from another class (parent class), promoting code reusability and establishing a hierarchy.

Code Example:

Code Example: Inheritance

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.");
    }
}

Output

Dog does not print output unless we create an instance of Dog and call methods:
Dog dog = new Dog();
dog.eat(); // This animal eats food.
dog.bark(); // The dog barks.

3. Polymorphism

Polymorphism allows methods to have multiple forms based on the object type. It can be achieved through method overloading (same method name, different parameters) and method overriding (same method name, same parameters in subclass).

Code Example:

Code Example: Polymorphism

public class Animal {
    public void sound() {
        System.out.println("Animal makes a sound");
    }
}

public class Cat extends Animal {
    @Override
    public void sound() {
        System.out.println("Cat meows");
    }
}

public class Dog extends Animal {
    @Override
    public void sound() {
        System.out.println("Dog barks");
    }
}

Output

Animal animal = new Cat(); animal.sound(); // Cat meows

4. Abstraction

Abstraction is the concept of hiding the complex reality while exposing only the necessary parts. In Java, abstraction can be achieved through abstract classes and interfaces.

Code Example:

Code Example: Abstraction

abstract class Shape {
    abstract void draw();
}

class Circle extends Shape {
    void draw() {
        System.out.println("Drawing a Circle");
    }
}

Output

(No direct output; you need to create an instance of Circle and call the draw method)
Shape circle = new Circle();
circle.draw(); // Drawing a Circle

Summary

Understanding and mastering OOP concepts in Java helps in designing and developing scalable and maintainable software systems.