Lesson 26 +10 XP

Classes and Objects

Classes and Objects

Java is an object-oriented language. Everything is organized around classes and objects.

Class vs object

  • A class is a blueprint or template for creating objects.
  • An object is an instance of a class.

A car is a class. A specific car, like "my red BMW", is an object created from that class.

Creating a class

public class Main {
  int x = 5;
}

The class Main has a field x.

Creating an object

Use the new keyword:

public class Main {
  int x = 5;

  public static void main(String[] args) {
    Main myObj = new Main();
    System.out.println(myObj.x); // 5
  }
}

Multiple objects

You can create many objects from one class, and each has its own values:

Main myObj1 = new Main();
Main myObj2 = new Main();
myObj2.x = 25;

TL;DR

  • A class is a blueprint; an object is a concrete instance.
  • Create objects with new ClassName().
  • Each object holds its own copy of the class fields.