Introduction to OOP: Classes vs. Objects

Learn Java OOP basics: difference between classes and objects with examples. Day 15 Java tutorial for beginners.
Introduction to OOP: Classes vs. Objects

On Day 15, we begin Object-Oriented Programming (OOP) in Java. OOP is a way of structuring programs around objects, which represent real-world entities, and classes, which define the blueprint for those objects. Understanding classes and objects is the foundation of Java development.

1. What is a Class?

A class is like a blueprint or template. It defines attributes (fields/variables) and behaviors (methods) of an object but does not occupy memory until an object is created.


class Car {
    // fields (attributes)
    String brand;
    int year;

    // method (behavior)
    void drive() {
        System.out.println(brand + " is driving!");
    }
}

2. What is an Object?

An object is an instance of a class. It has its own values for fields and can use the methods defined in the class.


public class Main {
    public static void main(String[] args) {
        // create objects
        Car car1 = new Car();
        car1.brand = "Toyota";
        car1.year = 2020;

        Car car2 = new Car();
        car2.brand = "Honda";
        car2.year = 2022;

        // use objects
        car1.drive();
        car2.drive();
    }
}

Explanation: Both car1 and car2 are objects of the class Car. Each has its own data but shares the same structure defined by the class.

3. Key Difference

  • Class: Blueprint (e.g., Car design)
  • Object: Real instance of the blueprint (e.g., Toyota, Honda cars)

Summary

Classes define structure and behavior, while objects are real entities created from classes. In Java, everything revolves around objects, making OOP a powerful approach for building scalable applications.

Post a Comment