Java Classes and Objects
Everything in a Java program lives inside a class, and every value you work with (other than primitives) is an object. In this lesson you will learn how to define your own class, how to create objects from it with the new keyword, and how multiple objects made from one class each keep their own independent data.
Defining a class
A class is defined with the 'class' keyword followed by a name and a pair of curly braces. By convention, class names start with a capital letter and use PascalCase, for example Car, BankAccount, or UserProfile. Inside the braces you list the class's attributes (its data) and methods (its behaviour). A class name should match the file name when the class is public, so a public class Car must live in a file called Car.java.
Defining a simple class
public class Car {
// attributes (fields)
String brand;
int year;
}Creating an object
A class by itself is only a description. To do anything useful you create an object - also called an instance - using the 'new' keyword. The new keyword allocates memory for the object and hands you back a reference to it, which you store in a variable. From that variable you reach the object's attributes and methods using the dot operator.
Creating and using an object
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // create an object
myCar.brand = "Toyota"; // set an attribute
myCar.year = 2024;
System.out.println(myCar.brand); // Toyota
System.out.println(myCar.year); // 2024
}
}Many objects from one class
One of the most important things to understand is that each object carries its own copy of the attributes. Changing the data of one object never affects another object made from the same class. In the example below, giving car2 a different brand leaves car1 completely untouched.
Independent objects
public class Main {
public static void main(String[] args) {
Car car1 = new Car();
car1.brand = "Honda";
Car car2 = new Car();
car2.brand = "Ford";
System.out.println(car1.brand); // Honda
System.out.println(car2.brand); // Ford
}
}- A class is the template; an object is a real instance built from it.
- Use the 'new' keyword to create an object.
- Access attributes and methods with the dot (.) operator.
- Each object stores its own independent copy of the attributes.
Exercise: Java Classes and Objects
What best describes the relationship between a class and an object?