Classes and objects are the two main aspects of object-oriented programming. A class is a blueprint for creating objects, and an object is an instance of a class.
Think of it this way:
To create a class, use the class keyword. By convention, class names in Java start with a capital letter.
In this example, we create a simple class named Car with a single attribute color.
public class Car {
String color = "red";
}
Note: The
Carclass itself won't produce any output on its own. In the live editor, it is wrapped in a smallMainclass so you can run it.
To create an object of a class, you specify the class name, followed by the object name, and use the new keyword.
The new keyword is a Java operator that creates the object.
Let's create an object called myCar from our Car class.
public class Main {
// The Car class definition
public static class Car {
String color = "red";
}
public static void main(String[] args) {
// Create an object of the Car class
Car myCar = new Car();
// Access the object's attributes and print them
System.out.println("The car's color is: " + myCar.color);
}
}
You can create multiple objects from one class.
public class Main {
static class Car {
String color = "red";
}
public static void main(String[] args) {
Car car1 = new Car();
Car car2 = new Car();
car2.color = "blue"; // Change the color of car2
System.out.println(car1.color); // Outputs "red"
System.out.println(car2.color); // Outputs "blue"
}
}