Java classes and objects explained
class definition, fields, methods, constructors, object instantiation, new keyword, this keyword, method signatures
Classes and Objects
A class is a blueprint. An object is a live instance created from that blueprint. Each object gets its own copy of the class's fields, while methods are shared across all instances.
Defining a Class
public class Car {
// Fields (state)
String make;
int year;
double mileage;
// Constructor
public Car(String make, int year) {
this.make = make;
this.year = year;
this.mileage = 0.0;
}
// Method (behavior)
public void drive(double km) {
mileage += km;
}
public String info() {
return year + " " + make + " — " + mileage + " km";
}
}
Creating and Using Objects
Car tesla = new Car("Tesla", 2023);
Car honda = new Car("Honda", 2019);
tesla.drive(500);
System.out.println(tesla.info()); // 2023 Tesla — 500.0 km
System.out.println(honda.info()); // 2019 Honda — 0.0 km
this refers to the current object inside a method or constructor. It disambiguates between a field and a parameter with the same name. If the parameter were named differently, this would be optional but is still good for clarity.
The new keyword allocates heap memory for the object and calls the constructor. The variable (tesla) holds a reference to that memory, not the object itself. Two variables can reference the same object — changes through one variable are visible through the other.
