Skip to main content

Command Palette

Search for a command to run...

Object-Oriented Programming (OOP) in Java

Updated
6 min read
A

I am an engineering student pursuing a degree in Artificial Intelligence and Data Science at Datta Meghe College of Engineering. I have strong technical skills in Full Stack Web Development, as well as programming in Python and Java. I currently manage Doubtly's blog and am exploring job opportunities as an SDE. I am passionate about learning new technologies and contributing to the tech community.

Welcome to the world of Object-Oriented Programming in Java! If you’re new to OOP or just need a refresher, this blog has got you covered. I’ll break down the concepts in a friendly way, so it feels like your buddy explaining it over coffee. 🍵


Introduction to OOP in Java

Object-Oriented Programming (OOP) is all about designing your program around objects and classes. Think of objects as the building blocks of your code—real-world things like cars, animals, or even bank accounts. And classes? They’re like the blueprints that define how those objects behave.

Key Principles of OOP:

  • Encapsulation: Hide the details, show the essentials.

  • Inheritance: Share and reuse code.

  • Polymorphism: One action, many forms.

  • Abstraction: Simplify complexity by focusing on the big picture.

OOP is a powerful programming paradigm because it lets you think in terms of real-world entities, making your code more intuitive, reusable, and scalable.


1. Classes and Objects: The Core of OOP

What is a Class?

A class is the blueprint for creating objects. It defines the attributes (fields) and behaviors (methods) of an object. Think of it as a recipe for making instances of something.

Example of a Class:

class Car {
    String brand;
    int speed;

    void displayDetails() {
        System.out.println("Brand: " + brand + ", Speed: " + speed);
    }
}

What is an Object?

An object is an instance of a class. It holds actual values for the attributes defined in the class.

Example of Creating and Using an Object:

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car(); // Create an object of the Car class
        myCar.brand = "Tesla";
        myCar.speed = 200;
        myCar.displayDetails();
    }
}

Output:

Brand: Tesla, Speed: 200

Objects are like real-world entities. For instance, if "Car" is a class, then "myCar" could be a Tesla Model S, complete with its own speed and brand attributes.


2. Method Overloading in Java

Method overloading is when you have multiple methods with the same name but different parameters. It’s like having multiple keys for different locks, but they’re all called "keys."

Why Use Method Overloading?

  • To increase readability.

  • To perform similar operations with different data inputs.

Example:

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

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

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

public class Main {
    public static void main(String[] args) {
        MathUtils utils = new MathUtils();
        System.out.println(utils.add(5, 10)); // Output: 15
        System.out.println(utils.add(5.5, 10.5)); // Output: 16.0
        System.out.println(utils.add(1, 2, 3)); // Output: 6
    }
}

3. Java Constructors: Building Objects

Constructors are special methods used to initialize objects. They share the same name as the class and have no return type. Constructors ensure that your object starts life with a valid state.

Types of Constructors:

Default Constructor:

A default constructor is automatically provided by Java if you don’t create one yourself. It initializes object fields with default values (e.g., 0 for integers, null for objects).

Example:

class Person {
    String name;

    Person() {
        name = "John Doe";
    }
}

Parameterized Constructor:

This type of constructor allows you to pass arguments when creating an object, making initialization more flexible.

Example:

class Person {
    String name;

    Person(String name) {
        this.name = name;
    }
}

Constructor Chaining: You can call one constructor from another using this() within the same class or super() for the parent class.


4. The this Keyword in Java

The this keyword refers to the current object. It’s like saying, "Hey, I’m talking about this thing here!"

Common Uses of this:

  1. To reference the current object’s fields.

  2. To call other constructors in the same class.

  3. To pass the current object as an argument.

Example:

class Person {
    String name;

    Person(String name) {
        this.name = name;
    }

    void introduce() {
        System.out.println("Hi, I’m " + this.name);
    }
}

5. Inheritance: Extending Classes in Java

Inheritance allows one class (child) to inherit the properties and methods of another (parent). This promotes reusability and a cleaner structure.

Syntax:

class ParentClass {
    // Parent class members
}

class ChildClass extends ParentClass {
    // Additional members
}

Example:

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

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();
    }
}

Output:

This animal eats food.
The dog barks.

6. Method Overriding: Customizing Behavior

When a subclass provides a specific implementation for a method in its parent class, that’s overriding. Overriding enables dynamic (runtime) polymorphism.

Rules for Overriding:

  1. The method must have the same name, return type, and parameters.

  2. The access modifier can’t be more restrictive.

  3. The method must not be final or static.

Example:

class Animal {
    void sound() {
        System.out.println("Some generic animal sound");
    }
}

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

7. The super Keyword in Java

Use super to call a parent class’s method or constructor.

Example:

class Animal {
    Animal() {
        System.out.println("Animal constructor called");
    }
}

class Dog extends Animal {
    Dog() {
        super(); // Calls parent constructor
        System.out.println("Dog constructor called");
    }
}

Output:

Animal constructor called
Dog constructor called

8. Comparing this vs. super

  • this refers to the current object.

  • super refers to the parent class.

Quick Comparison:

Featurethissuper
Refers toCurrent objectParent class
Used forAccessing current class’s membersAccessing parent’s members
CallsCurrent class constructorsParent class constructors

9. The final Keyword: Constants and More

The final keyword is versatile in Java. Let’s break it down:

  • Final Variables: Can’t be reassigned.

  • Final Methods: Can’t be overridden.

  • Final Classes: Can’t be subclassed.

Example:

final class Constants {
    static final double PI = 3.14159;
}

10. Practice Makes Perfect!

Exercise:

  1. Create a class Shape with a method area().

  2. Extend it with Circle and Rectangle classes, overriding the area() method.

  3. Use inheritance and polymorphism to calculate the areas of a circle and rectangle.

Drop your solutions in the comments! 😎

OOP concepts may seem tricky at first, but with practice, they’ll become second nature. Keep coding, and you’ll soon be an OOP wizard! 🎩


Final Words

The key to mastering OOP in Java is understanding the "why" behind each concept and applying it in real-life scenarios. Each principle builds upon the other, creating a robust foundation for designing scalable and efficient programs. Now, it’s time for you to dive into coding, explore these concepts, and unleash your creativity! 🚀

More from this blog

U

UniGeek

29 posts

Unigeek empowers developers and tech enthusiasts at every level. From placement prep and daily coding challenges to advanced upskilling, Unigeek helps you grow in the ever-evolving tech world.