Classes and Objects
Classes and Objects
Java is object-oriented. A class is a blueprint that describes the data (fields) and behavior (methods) of something. An object is a concrete instance of that class, created with new.
Defining a class
A class can have fields (variables that belong to each object) and methods. Here is a simple class:
javapublic class Car { String brand; int year; public Car(String brand, int year) { this.brand = brand; this.year = year; } }
brandandyearare instance fields: eachCarobject has its own copy.public Car(String brand, int year)is a constructor. It has the same name as the class and no return type. It runs when you create a newCarwithnew Car(...).this.brandandthis.yearrefer to the fields of the object being constructed. Usingthisavoids confusion when parameter names match field names.
Creating objects
You create an object with the new keyword and the constructor:
javaCar myCar = new Car(\"Toyota\", 2020); System.out.println(myCar.brand); // Toyota System.out.println(myCar.year); // 2020
myCar is a reference to a Car object. You access fields and methods with a dot: myCar.brand, myCar.year.
Multiple constructors
A class can have more than one constructor. Each has a different parameter list. This is another form of overloading.
javapublic class Car { String brand; int year; public Car(String brand, int year) { this.brand = brand; this.year = year; } public Car(String brand) { this.brand = brand; this.year = 2020; // default } }
Then you can call new Car(\"Tesla\", 2023) or new Car(\"Tesla\").
null
A reference that does not point to any object has the value null. Using a null reference (e.g. calling a method on it) causes a NullPointerException at runtime. Always ensure an object is not null before using it, or use optional types and checks as you learn more. In the next lesson we will use lists (collections) to store many objects.