DEV Community

Subash
Subash

Posted on

Object in Java

Object in Java

In Java, an object is an instance of a class. It represents a real-world entity and has state (data) and behavior (methods).

For example, a car can have properties like its color and brand, and behaviors like starting and stopping.

Example

Let's create a simple Java class and an object.

class Car {
String brand = "BMW";
String color = "Black";

void start() {
    System.out.println("The car is starting");
}
Enter fullscreen mode Exit fullscreen mode

}

public class Main {
public static void main(String[] args) {
Car myCar = new Car();

    System.out.println(myCar.brand);
    System.out.println(myCar.color);

    myCar.start();
}
Enter fullscreen mode Exit fullscreen mode

}

Output

BMW
Black
The car is starting

Understanding the code

Class: Car is a blueprint for creating car objects.

Object: myCar refers to the object created using new Car().

State: brand and color represent the object's data.

Behavior: start() is a method that represents what the object can do.

new keyword: It creates a new Car object.

Conclusion

A class defines the structure, while an object is an instance of that class. Objects help us represent real-world entities and organize code using object-oriented programming (OOP).

Top comments (0)