Classes and Objects

In this tutorial, you’ll learn about the building blocks of Java programming: classes and objects.

What are Classes and Objects?

A class is a blueprint for objects. It defines a datatype by bundling data and methods that work on the data into one single unit. An object is an instance of a class.

Defining a Class

To define a class, use the class keyword:


public class Car {
    // fields
    String color;
    String model;
    
    // methods
    void drive() {
        System.out.println("Driving the car");
    }
}
      

Creating an Object

To create an object, use the new keyword:


public class Main {
    public static void main(String[] args) {
        Car myCar = new Car();
        myCar.color = "Red";
        myCar.model = "Toyota";
        myCar.drive();
    }
}
      

In the example above, myCar is an object of the class Car.

Constructors

A constructor is a special method that is called when an object is instantiated. It can be used to set initial values for object attributes:


public class Car {
    String color;
    String model;
    
    // Constructor
    public Car(String color, String model) {
        this.color = color;
        this.model = model;
    }
}
      

Access Modifiers

Access modifiers specify the accessibility of a class, method, or field. The four access modifiers in Java are:

  • public – accessible from anywhere
  • protected – accessible within the same package and subclasses
  • default – accessible only within the same package
  • private – accessible only within the same class

Continue exploring our intermediate tutorials to learn more about Java programming.

Scroll to Top