Beginner
Classes and Objects
📂 Phase 3: Object-Oriented Programming (Days 11–16) · JavaA class is a blueprint that defines the properties (fields) and behaviors (methods) that its objects will have. An object is a concrete instance created from that blueprint, holding its own actual data.
Defining a Class
public class Car {
// Fields (also called instance variables / attributes)
String color;
String model;
int speed;
// Method (behavior)
void accelerate() {
speed += 10;
System.out.println(model + " is now going " + speed + " km/h");
}
}
Creating Objects
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // creates an object of Car
myCar.color = "Red";
myCar.model = "Civic";
myCar.speed = 0;
myCar.accelerate(); // Civic is now going 10 km/h
}
}
Multiple Objects, Independent State
Every object created from a class has its own copy of the instance variables — changing one object's fields never affects another object of the same class.
Car car1 = new Car();
car1.model = "Civic";
Car car2 = new Car();
car2.model = "Mustang";
System.out.println(car1.model); // Civic
System.out.println(car2.model); // Mustang — completely independent
Constructors
A constructor is a special method, matching the class name, that runs automatically when an object is created — used to initialize fields immediately rather than setting them one by one.
public class Car {
String model;
int speed;
// Constructor
public Car(String model) {
this.model = model;
this.speed = 0;
}
}
Car myCar = new Car("Civic"); // model is set immediately
System.out.println(myCar.model); // Civic
The this Keyword
this refers to the current object — it's used to distinguish a field from a parameter that shares the same name, as seen in this.model = model; above.
Interview tip: If you don't write any constructor, Java automatically provides a no-argument "default constructor" — but as soon as you write any constructor yourself, that automatic default disappears.