OOP Basics — Classes & Objects
Classes and Objects
A class is a blueprint that defines the state (fields) and behavior (methods) of objects. An object is a concrete instance of a class created with the new keyword.
public class Car {
// Instance fields (state)
String brand;
String model;
int year;
double price;
// Default constructor (no parameters)
public Car() {
brand = "Unknown";
model = "Unknown";
year = 2000;
price = 0.0;
}
// Parameterized constructor
public Car(String brand, String model, int year, double price) {
this.brand = brand; // 'this' refers to the current object
this.model = model;
this.year = year;
this.price = price;
}
// Copy constructor
public Car(Car other) {
this.brand = other.brand;
this.model = other.model;
this.year = other.year;
this.price = other.price;
}
// Instance method (behavior)
public void displayInfo() {
System.out.printf("%s %s (%d) — $%.2f%n", brand, model, year, price);
}
public static void main(String[] args) {
Car c1 = new Car(); // default constructor
Car c2 = new Car("Toyota", "Camry", 2023, 26000.0); // parameterized
Car c3 = new Car(c2); // copy constructor
c1.displayInfo(); // Unknown Unknown (2000) — $0.00
c2.displayInfo(); // Toyota Camry (2023) — $26000.00
c3.displayInfo(); // Toyota Camry (2023) — $26000.00
}
}
The this Keyword
this is a reference to the current object. It has three main uses:
public class Person {
String name;
int age;
String email;
// Full constructor
public Person(String name, int age, String email) {
this.name = name;
this.age = age;
this.email = email;
}
// Delegates to full constructor using this()
public Person(String name, int age) {
this(name, age, "not provided"); // must be first line
}
// Delegates further
public Person(String name) {
this(name, 0);
}
@Override
public String toString() {
return name + " | age=" + age + " | email=" + email;
}
public static void main(String[] args) {
System.out.println(new Person("Alice", 30, "alice@example.com"));
System.out.println(new Person("Bob", 25));
System.out.println(new Person("Charlie"));
}
}
Ready to Level Up Your Skills?
Explore 500+ free tutorials across 20+ languages and frameworks.