Object in java with example
Follow Our Java Series.
In Java, an object is an instance of a class. It’s a fundamental concept in object-oriented programming (OOP). Here’s an example to illustrate:
// Defining a class
class Car {
String brand;
String model;
int year;
// Constructor
public Car(String brand, String model, int year) {
this.brand = brand;
this.model = model;
this.year = year;
}
// Method to display information about the car
public void displayInfo() {
System.out.println("Brand: " + brand + ", Model: " + model + ", Year: " + year);
}
}
public class Main {
public static void main(String[] args) {
// Creating an object of the Car class
Car myCar = new Car(“Toyota”, “Corolla”, 2020);
// Accessing object properties and methods
System.out.println("My car is a " + myCar.brand + " " + myCar.model);
myCar.displayInfo();
}
}
In this example, Car is a class with three attributes (brand, model, year) and a constructor to initialize these attributes. The displayInfo method is used to print information about the car. In the Main class, we create an object myCar of the Car class using the new keyword. We then access the object’s properties (brand and model) and call its method (displayInfo) to display its information.