Learn Object Oriented Programming (OOP) in Java

Understanding Object Oriented Programming (OOP) Concepts in Java

Object oriented programming, often referred to as OOP, is a fundamental concept in modern software development. It’s a programming paradigm that uses “objects” to represent data and methods to manipulate that data. Java, as one of the most popular programming languages, is renowned for its robust support of OOP principles. In this article, we will explore the key concepts of OOP in Java, its significance, and how it can enhance your programming skills.

What is Object Oriented Programming?

Object-oriented programming is a method of programming that organizes software design around data, or objects, rather than functions and logic. An object can be defined as a data field that has unique attributes and behavior. This paradigm allows developers to create modular programs and reusable code.

Importance of OOP in Modern Software Development

OOP is crucial in modern software development because it promotes greater flexibility and maintainability in code. By organizing software design around objects, developers can more easily manage complex systems and ensure code reusability, which saves time and effort in the long run.

The Four Pillars of Object Oriented Programming (OOP)

Understanding the four main principles of OOP is essential for mastering Java programming. These pillars are encapsulation, inheritance, polymorphism, and abstraction.

Object Oriented Programming-Concept-four-Pillars-by-datavaani
Object Oriented Programming

Java as an Object Oriented Programming Language

Overview of Java

Java is a high-level, class-based, and object-oriented programming language that is designed to have as few implementation dependencies as possible. It is widely used for building enterprise-scale applications and has a rich set of APIs and a large community.

Why Java is Ideal for OOP

Java is designed from the ground up to support OOP principles. It provides a clear structure for programs and allows code to be reused, making the development process more efficient. Java’s syntax is simple and easy to understand, which makes it an ideal language for learning and implementing OOP concepts.

Classes and Objects in Java

Definition and Importance

In Java, a class is a blueprint from which individual objects are created. A class defines a type of object according to the attributes and methods that the objects of this class will have. Objects are instances of classes.

Creating Classes and Objects in Java

To create a class in Java, you define a class with the class keyword, followed by the class name and a pair of curly braces containing the class’s attributes and methods. For example:

Car myCar = new Car();
myCar.color = "red";
myCar.accelerate();
Java

To create an object of this class, you use the new keyword:

Car myCar = new Car();
myCar.color = "red";
myCar.accelerate();
Java

Encapsulation in Java

Definition and Benefits

Encapsulation ensures that the internal representation of an object is hidden from the outside. Only the object’s methods can access and modify its fields. This control of access helps to protect the integrity of the object’s data.

Implementing Encapsulation in Java

In Java, you can implement encapsulation by making the fields of a class private and providing public getter and setter methods to modify and view the values of these fields.

public class Person {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int newAge) {
        age = newAge;
    }
}
Java

Inheritance in Java

Definition and Types

Inheritance is a fundamental feature of Object Oriented Programming (OOP) where a new class (subclass) inherits the attributes and methods of an existing class (superclass). There are different types of inheritance in Java: single inheritance, multilevel inheritance, and hierarchical inheritance.

Implementing Inheritance in Java

To implement inheritance in Java, use the extends keyword. Here’s an example:

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

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

public class Main {
    public static void main(String[] args) {
        Dog myDog = new Dog();
        myDog.eat();
        myDog.bark();
    }
}
Java

Polymorphism in Java

Definition and Examples

Polymorphism, a cornerstone of object-oriented programming (OOP), empowers you to write adaptable and reusable code in Java. It allows objects of different classes to respond to the same method call in distinct ways. Let’s delve into the world of polymorphism and explore its practical applications in Java.

Understanding Polymorphism:

Imagine having a remote control for various electronic devices (TV, sound system, etc.). You press the “power” button, but each device reacts differently. This is the essence of polymorphism. A single method call (pressing the button) triggers unique behaviors based on the specific object (the device) being controlled.

Implementing Polymorphism in Java

In Java, polymorphism manifests in two primary forms:

Method Overriding:

  • A subclass (child class) inherits methods from its parent class.
  • The subclass can redefine (override) inherited methods to provide its own implementation.
  • When a method is called on a reference variable of the parent class type, the actual object’s (subclass) overridden method is executed at runtime.

Example:

class Animal {
    public void makeSound() {
        System.out.println("Generic animal sound");
    }
}

class Dog extends Animal {
    @Override // Explicitly declares overriding
    public void makeSound() {
        System.out.println("Woof!");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal myAnimal = new Dog(); // Upcasting (parent reference to child object)
        myAnimal.makeSound(); // Outputs: Woof! (Dog's overridden method)
    }
}
Java

Method Overloading:

  • A class can have multiple methods with the same name but different parameter lists (number, type, or order of parameters).
  • The compiler determines the appropriate method to call based on the arguments provided at runtime.

Example:

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

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

public class Main {
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        System.out.println(calc.add(5, 3)); // Outputs: 8 (int + int)
        System.out.println(calc.add(2.5, 1.7)); // Outputs: 4.2 (double + double)
    }
}
Java
Benefits of Polymorphism:
  • Code Reusability: By overriding methods, you can leverage existing functionality while adding specific behaviors in subclasses.
  • Flexibility: Polymorphism allows code to adapt to different object types without extensive modifications.
  • Maintainability: Code becomes easier to understand and modify as functionalities are encapsulated within their respective classes.

By mastering polymorphism, you can write cleaner, more dynamic, and robust Java applications. So, leverage the power of polymorphism to elevate your code to the next level!

Abstraction in Java

Definition and Advantages

Abstraction focuses on hiding the complex implementation details and showing only the essential features of the object. It reduces programming complexity and effort.

Implementing Abstraction in Java

In Java, abstraction can be achieved using abstract classes and interfaces.

interface Shape {
  double calculateArea();
}

class Square implements Shape {
  private final double sideLength;

  public Square(double sideLength) {
    this.sideLength = sideLength;
  }

  @Override
  public double calculateArea() {
    return sideLength * sideLength;
  }
}

class Circle implements Shape {
  private final double radius;

  public Circle(double radius) {
    this.radius = radius;
  }

  @Override
  public double calculateArea() {
    return Math.PI * radius * radius;
  }
}

public class ShapeCalculator {

  public static void calculateAndPrintArea(Shape shape) {
    System.out.println("Area: " + shape.calculateArea());
  }

  public static void main(String[] args) {
    Shape square = new Square(5);
    Shape circle = new Circle(3);

    calculateAndPrintArea(square);
    calculateAndPrintArea(circle);
  }
}
Java
Explanation of above code:
  • This example uses an interface (Shape) to define the contract for calculating the area.
  • Concrete classes (Square and Circle) implement the Shape interface, providing their own implementations for calculateArea.
  • The ShapeCalculator class operates solely on the Shape interface, allowing it to work with any object that implements Shape without knowing the specific implementation details (square vs circle).
  • This highlights the power of abstraction in promoting code reusability and flexibility.

Conclusion

As you delve deeper into Java programming, continue to explore and experiment with Object Oriented Programming (OOP) concepts. Practice by building your own Java projects that utilize these principles. Remember, the more you practice, the more comfortable and proficient you’ll become in crafting robust and efficient Java applications using the power of OOP.

Frequently Asked Question – FAQ