Course contentsShow
← Java
Lesson 308 of 2,8708. Classes and EncapsulationFree lesson

Methods: Defining Behavior in Classes

Creating methods within classes to define operations that objects can perform.

Methods: Defining Behavior in Classes

What You'll Learn

You'll learn how to create methods inside classes to give your objects the ability to do things.

The Core Idea

A class isn't just about storing data in fields—it's also about defining behavior. Methods are functions that belong to a class and describe what objects of that class can do. If fields answer "what does this object know?", methods answer "what can this object do?"

Think of a BankAccount class. Its fields might store the account balance and owner name (what it knows). But methods like deposit, withdraw, and checkBalance define what actions you can perform with that account (what it can do).

Method Syntax in a Class

A method inside a class looks just like the methods you've been writing, but now they're tied to objects:

class Dog {
    String name;
    int age;
    
    void bark() {
        System.out.println(name + " says: Woof!");
    }
    
    void celebrate() {
        System.out.println(name + " is " + age + " years old!");
    }
}

Notice that bark() and celebrate() can access the fields name and age directly—they're part of the same class.

Using Methods

When you create an object, you can call its methods using the dot operator:

Dog myDog = new Dog();
myDog.name = "Buddy";
myDog.age = 3;
myDog.bark();        // Prints: Buddy says: Woof!
myDog.celebrate();   // Prints: Buddy is 3 years old!

Each Dog object has its own name and age, so calling bark() on different dogs produces different output.

Key Takeaway: Methods define the operations objects can perform, giving classes both data (fields) and behavior (methods) to create meaningful, functional objects.