Java Classes and Objects

Java Classes and Objects

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:


Creating a Class

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.

Creating a `Car` Class

public class Car {
  String color = "red";
}

Note: The Car class itself won't produce any output on its own. In the live editor, it is wrapped in a small Main class so you can run it.


Creating an Object

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.

Creating an Object

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);
  }
}

Using Multiple Objects

You can create multiple objects from one class.

Multiple Objects

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" } }