Java Learner logo

Module 5: Object-Oriented Programming (OOP) Fundamentals

Lesson focus

Classes and Objects in Practice

Move from theory to practice by creating your own classes, instantiating objects, and using their fields and methods.

Creating a Class: A class is defined using the class keyword. Inside the class, you define fields (variables) to hold the state of an object and methods to define its behavior.

Fields (Instance Variables): These are variables declared inside a class but outside any method. Each object (instance) of the class gets its own copy of these fields.

Instantiating an Object: You create an object from a class using the new keyword, followed by a call to the class constructor. ClassName objectName = new ClassName();

Accessing Members: You use the dot (.) operator to access an object's fields and methods. objectName.fieldName or objectName.methodName().

class Car {
    String color;
    int year;

    void startEngine() {
        System.out.println("Engine started!");
    }
}

public class Garage {
    public static void main(String[] args) {
        // Create an instance of the Car class
        Car myCar = new Car();
        myCar.color = "Red";
        myCar.year = 2023;

        System.out.println("My car is " + myCar.color);
        myCar.startEngine();
    }
}

Lesson quiz

What keyword is used to create an instance of a class?

Next lesson →