Java OOP Concepts


Java OOP Concepts

Object-Oriented Programming (OOP) is a programming model built around the idea of objects that encapsulate both data (attributes) and functionality (methods). Java is a widely used object-oriented language, and its OOP principles enhance code modularity, reusability, and readability.

The core principles of Java's OOP are:


1. Class and Object

  • Class: A blueprint for creating objects. It defines properties (attributes) and behaviors (methods) common to all objects of that type.
  • Object: An instance of a class. It represents real-world entities with specific values for the attributes defined in the class.

Syntax for Class:

class ClassName {
    // Fields (attributes)
    // Methods (behaviors)
}

Example of Class and Object:

public class Car {
    String brand;  // Attribute
    int speed;     // Attribute

    void displayDetails() {  // Method
        System.out.println("Brand: " + brand);
        System.out.println("Speed: " + speed + " km/h");
    }

    public static void main(String[] args) {
        Car myCar = new Car(); // Creating an object
        myCar.brand = "Tesla";
        myCar.speed = 150;
        myCar.displayDetails();
    }
}

Output:

Brand: Tesla
Speed: 150 km/h

2. Inheritance

Inheritance allows a class to acquire the properties and behaviors of another class. It enables code reuse and establishes a relationship between parent (superclass) and child (subclass) classes.

Syntax:

class ParentClass {
    // Fields and methods
}

class ChildClass extends ParentClass {
    // Additional fields and methods
}

Example:

class Animal {
    void eat() {
        System.out.println("This animal eats food.");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("This dog barks.");
    }
}

public class InheritanceExample {
    public static void main(String[] args) {
        Dog myDog = new Dog();
        myDog.eat(); // Inherited method
        myDog.bark(); // Dog-specific method
    }
}

Output:

This animal eats food.
This dog barks.

3. Encapsulation

Encapsulation is the process of wrapping data (fields) and methods in a single unit (class) and restricting access to the fields using access modifiers. It ensures data security by exposing only necessary parts through methods (getters and setters).

Syntax:

class ClassName {
    private dataType fieldName;

    // Getter
    public dataType getFieldName() {
        return fieldName;
    }

    // Setter
    public void setFieldName(dataType value) {
        fieldName = value;
    }
}

Example:

public class Person {
    private String name;

    // Getter
    public String getName() {
        return name;
    }

    // Setter
    public void setName(String newName) {
        name = newName;
    }

    public static void main(String[] args) {
        Person person = new Person();
        person.setName("Alice");
        System.out.println("Name: " + person.getName());
    }
}

Output:

Name: Alice

4. Polymorphism

Polymorphism means "many forms" and allows methods or objects to behave differently based on their context. It is achieved through:

  • Method Overloading: Method Overloading involves using the same method name but with different parameter sets.
  • Method Overriding: Method Overriding enables a subclass to implement its own version of a method that is already defined in its parent class.

Example of Method Overloading:

class Calculator {
    int add(int a, int b) {
        return a + b;
    }

    double add(double a, double b) {
        return a + b;
    }
}

public class OverloadingExample {
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        System.out.println("Sum (int): " + calc.add(5, 10));
        System.out.println("Sum (double): " + calc.add(5.5, 10.2));
    }
}

Output:

Sum (int): 15
Sum (double): 15.7

Example of Method Overriding:

class Vehicle {
    void run() {
        System.out.println("Vehicle is running.");
    }
}

class Car extends Vehicle {
    @Override
    void run() {
        System.out.println("Car is running fast.");
    }
}

public class OverridingExample {
    public static void main(String[] args) {
        Vehicle myCar = new Car(); // Polymorphic behavior
        myCar.run();
    }
}

Output:

Car is running fast.

5. Abstraction

Abstraction emphasizes exposing only critical details while concealing the underlying implementation. This can be achieved through:

  • Abstract classes: Defined using the abstract keyword and may contain both abstract (unimplemented) and concrete methods.
  • Interfaces: Fully abstract classes where all methods are abstract.

Syntax for Abstract Class:

abstract class ClassName {
    abstract void abstractMethod(); // No implementation
}

Example of Abstract Class:

abstract class Shape {
    abstract void draw();
}

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

public class AbstractExample {
    public static void main(String[] args) {
        Shape shape = new Circle();
        shape.draw();
    }
}

Output:

Drawing a circle.

Syntax for Interface:

interface InterfaceName {
    void methodName(); // Implicitly abstract
}

Example of Interface:

interface Animal {
    void sound();
}

class Cat implements Animal {
    public void sound() {
        System.out.println("Meow");
    }
}

public class InterfaceExample {
    public static void main(String[] args) {
        Animal animal = new Cat();
        animal.sound();
    }
}

Output:

Meow

6. Association, Aggregation, and Composition

These concepts define relationships between classes:

  • Association: A general relationship where one class interacts with another.
  • Aggregation: A "has-a" relationship where one class contains another as a part, but both can exist independently.
  • Composition: A stronger form of aggregation where the lifecycle of one class depends on the other.

Example of Composition:

class Engine {
    void start() {
        System.out.println("Engine starts.");
    }
}

class Car {
    private Engine engine = new Engine(); // Composition

    void drive() {
        engine.start();
        System.out.println("Car is moving.");
    }
}

public class CompositionExample {
    public static void main(String[] args) {
        Car car = new Car();
        car.drive();
    }
}

Output:

Engine starts.
Car is moving.

Conclusion

Java's OOP concepts — encapsulation, inheritance, polymorphism, and abstraction — form the backbone of its object-oriented nature. By using these principles, you can create flexible, reusable, and maintainable code that mirrors real-world scenarios.

PreviousNext