You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Java is fundamentally an object-oriented language. Almost everything in Java is an object — instances of classes that bundle data (fields) and behaviour (methods) together. This lesson covers classes, objects, constructors, encapsulation, and the this keyword.
A class is a blueprint; an object is an instance of that blueprint.
public class Car {
// Fields (instance variables)
String make;
String model;
int year;
// Method
void describe() {
System.out.println(year + " " + make + " " + model);
}
}
Car myCar = new Car();
myCar.make = "Toyota";
myCar.model = "Corolla";
myCar.year = 2024;
myCar.describe(); // "2024 Toyota Corolla"
A constructor is a special method called when you create an object with new. It initialises the object's fields.
public class Car {
String make;
String model;
int year;
// Constructor
public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
void describe() {
System.out.println(year + " " + make + " " + model);
}
}
// Usage:
Car myCar = new Car("Toyota", "Corolla", 2024);
myCar.describe();
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.