What exactly is an Object in Java?

In Java, an object is a real-world entity that has:

  • State (also called attributes or fields)
  • Behavior (also called methods or functions)
  • Identity (each object is unique, even if they have the same state)

๐Ÿ”น Example from real life:

Car

  • State: color = red, speed = 80km/h
  • Behavior: accelerate(), brake()

So, a car object in Java would hold this information and define how the car behaves.


๐Ÿ”ธ In Java terms:

An object is an instance of a class.

class Car {
ย  ย  String color;
ย  ย  int speed;

ย  ย  void accelerate() {
ย  ย  ย  ย  speed += 10;
ย  ย  }
}

public class Main {
ย  ย  public static void main(String[] args) {
ย  ย  ย  ย  Car myCar = new Car(); // object created
ย  ย  ย  ย  myCar.color = "Red";
ย  ย  ย  ย  myCar.speed = 80;
ย  ย  ย  ย  myCar.accelerate(); ย  ย // method call
ย  ย  }
}


๐Ÿง  Summary:

  • Class = blueprint
  • Object = actual product built using the blueprint
  • Objects are stored in heap memory

ย 

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.