r/learnjava 12d ago

Java Beginners: What Is an Object Actually?

I'm a Java learner and I've been learning Java for the past few months, but I still don't truly understand what an object actually is.

I've watched several YouTube videos and used AI tools to understand it, but I keep getting the same explanation: "An object is nothing but data + code."

I understand the definition, but I still can't visualize or feel what an object actually is when I'm writing Java code.

Could someone explain it in a simple, practical way, preferably with a real world analogy and a small Java example?

I feel like I'm missing one fundamental concept here. Any explanation would be really helpful. Thanks!

4 Upvotes

43 comments sorted by

View all comments

1

u/invertedfretboard313 12d ago edited 12d ago

A class is like a cookie cutter you can write many as many attributes you want in class. Suppose we have class Car

public class Car {
    float speed;
    String brand;
    String colour;

    void ignition() {
        System.out.println("Engine has been started");
    }

    void accelerate() {
        speed += 10;
        System.out.println(brand + " is now going " + speed + " km/h");
    }

    void brake() {
        speed -= 10;
        System.out.println(brand + " slowed down to " + speed + " km/h");
    }
}

You can create objects using the new keyword. For example

Car myCar = new Car();
myCar.brand = "Toyota";
myCar.colour = "Red";
myCar.speed = 0;

Car car2 = new Car();
car2.brand = "Honda";
car2.colour = "Blue";
car2.speed = 0;

myCar and car2 are both actual instances of Car that now exist in memory.

Even though myCar and car2 came from the same class, they are separate objects with their own speed, brand and colour so changing one never touches the other

Now you can call the methods by following code:

myCar.ignition();     // Engine has been started
myCar.accelerate();   // Toyota is now going 10.0 km/h

car2.ignition();      // Engine has been started
car2.accelerate();    // Honda is now going 10.0 km/h
car2.brake();         // Honda slowed down to 0.0 km/h

System.out.println(myCar.speed); // 10.0
System.out.println(car2.speed);  // 0.0