Java Classes & Objects

Fields, constructors and methods.

✍️ 2 exercises in this lesson

Java is built around classes (blueprints) and objects (instances).

  • Fields store data; methods define behaviour.
  • A constructor has the class name and no return type; it initialises a new object.
  • this refers to the current object.
  • Create objects with new.
  • static members belong to the class, not to individual objects.

Key Takeaways: Java Classes & Objects

Mastering Java Classes & Objects helps you write clean and reliable Java code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Java Classes & Objects Code Example

Java
class Car {
    String brand;
    int year;
    static int count = 0;

    Car(String brand, int year) {
        this.brand = brand;
        this.year = year;
        count++;
    }

    int age(int currentYear) {
        return currentYear - year;
    }
}

public class Main {
    public static void main(String[] args) {
        Car a = new Car("Toyota", 2019);
        Car b = new Car("Honda", 2022);
        System.out.println(a.brand + " is " + a.age(2026) + " years old");
        System.out.println(b.brand + " is " + b.age(2026) + " years old");
        System.out.println("Cars created: " + Car.count);
    }
}
Output
Toyota is 7 years old
Honda is 4 years old
Cars created: 2
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

Java Classes & Objects Practice Exercises

Check what you learned in “Java Classes & Objects”.

/ 2 solved
Fill in the blank

Create an object.

Car c =  Car("Honda", 2022);
✓ Correct! Not quite. Try again.
Multiple choice

What is a constructor?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services