In Java, an object is an instance of a class that has its own identity, behavior, and state. A class is a blueprint for creating objects, and it describes the behavior and state that the objects of its type support. Here is an example of a class and object in Java:
public class Car {
String color;
int weight;
public void drive() {
System.out.println("The car is driving.");
}
public void brake() {
System.out.println("The car is braking.");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.color = "red";
myCar.weight = 2000;
myCar.drive();
myCar.brake();
}
}
In this example, we have created a class called Car
that has two attributes (color
and weight
) and two methods (drive
and brake
). We then create an object of the Car
class called myCar
and set its attributes to "red" and 2000. Finally, we call the drive
and brake
methods on the myCar
object. When we run this program, it will output:
The car is driving.
The car is braking.