OOP: Classes & Objects
Java is built entirely around Object-Oriented Programming (OOP). OOP organizes software around data models called objects, which are instances of structures called classes.
1 Classes, Instances, and Constructors
A **Class** is a blueprint/template. An **Object** is the concrete instance created in heap memory from that template using the `new` keyword. Classes contain:
- Fields (Instance Variables): The data states of the object.
- Constructors: Special initialization methods block invoked when creating objects. Constructors match the class name exactly and have no return type.
- Methods: Behaviors the object can execute.
2 Constructor Chaining using this()
You can define multiple constructors (overloading). Using the keyword `this()` as the first line inside a constructor allows you to call another constructor inside the same class. This is called constructor chaining and reduces duplicate code. Let's inspect object construction:
Java — OOP Classes & Objects
▶ Run Code
class Car {
String model;
int year;
// Parameterized Constructor
Car(String model, int year) {
this.model = model;
this.year = year;
}
// Overloaded Constructor calling the main one (Chaining)
Car(String model) {
this(model, 2026); // Default year to 2026
}
void displayInfo() {
System.out.println("Car model: " + model + ", Year: " + year);
}
}
public class Main {
public static void main(String[] args) {
// Instantiate using parameterized constructor
Car myCar1 = new Car("Toyota Supra", 2022);
// Instantiate using chained constructor
Car myCar2 = new Car("Tesla Model S");
myCar1.displayInfo();
myCar2.displayInfo();
}
}
3 Code Challenge
Challenge: Write a class representing a `Student`. Give it two fields: `String name` and `int gradeLevel`. Create a main constructor that accepts both, and a default chained constructor that takes only a name and passes a default grade level of 1. Write an instance method showing student details, instantiate both students, and print details.