Start learning free

LESSON 180 OF 344 · OBJECT-ORIENTED PROGRAMMING

Class Methods in Java: Adding Behavior to Objects

Lesson Read the full explanation

TL ; DR:

  • A method is a function that lives inside a class. Each object can call its methods, and the methods can read and write the object's fields.


  • Define a method like a regular function, but inside the class body:

    class Dog {
        public String name;
    
        public void bark() {
            System.out.println("Woof! I am " + name);
        }
    }
    

  • Call it on an object with the dot operator: dog.bark();



Full lesson:

So far you've added data to a class with fields and constructors. The other half of OOP is behavior — actions an object can perform. That's what methods are for.


Defining a method

class Dog {
    public String name;

    public void bark() {
        System.out.println("Woof! I am " + name);
    }
}

The method can directly read the name field. When you call rex.bark(), the method sees rex's name.


Your task

Add a bark() method to Dog that prints "Woof! I am " followed by the dog's name.

Woof! I am Rex
STEP 1 OF 2
    Ctrl + Enter to check

    JAVA · OBJECT-ORIENTED PROGRAMMING

    Class Methods in Java, explained

    What a method is

    Fields and constructors give an object its data. A method gives it behavior: an action the object can perform. A method is a function declared inside a class, and it can read and change the fields of the object it is called on.

    Defining a method

    A method sits in the class body, next to the fields and constructors:

    class Dog {
        public String name;
    
        public void bark() {
            System.out.println("Woof! I am " + name);
        }
    }
    

    Reading the header public void bark() from left to right:

    • public means code outside the class may call the method;
    • void is the return type and means the method gives nothing back. A method that returns a value names that type here instead, such as int or String;
    • bark is the name, written in camelCase by convention;
    • () holds the parameters, and this method takes none.

    The body, between the braces, can use the object's fields by their bare names. Writing name inside bark means the same as this.name.

    Calling a method

    You call a method on an object with the dot operator, followed by parentheses:

    Dog rex = new Dog("Rex");
    rex.bark();
    

    Inside bark, the field name belongs to the object the call was made on, so rex.bark() sees rex's name. Two dogs with different names bark differently, even though the method code is written only once.

    Methods with parameters and results

    A method can take input and give back a value. Here is a small class that does both:

    class Cat {
        public String name;
        public int age;
    
        public Cat(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public void birthday() {
            age++;
        }
    
        public String describe() {
            return name + " is " + age;
        }
    }
    

    Calling these on a cat shows the effect of the first on the second:

    Cat tom = new Cat("Tom", 1);
    tom.birthday();
    System.out.println(tom.describe());
    
    Tom is 2
    

    birthday changes the object's state, and describe reports it with a return statement. The value after return must match the declared return type, here String.

    The lesson's exercise, step by step

    The starter code gives Dog a name field and a constructor, and its mainFunction already calls rex.bark(). The method itself is missing, so the program doesn't compile yet. There are two steps:

    1. Declare the method. Below the constructor, write public void bark() with an empty body. It takes no parameters and returns nothing.
    2. Fill in the body. Print "Woof! I am " joined with the name field, using System.out.println.

    The finished program:

    class Dog {
        public String name;
    
        public Dog(String name) {
            this.name = name;
        }
    
        public void bark() {
            System.out.println("Woof! I am " + name);
        }
    }
    
    class Solution {
        public void mainFunction() {
            Dog rex = new Dog("Rex");
            rex.bark();
        }
    }
    

    Running it prints:

    Woof! I am Rex
    

    The + between a String and another value builds one longer string, so the greeting and the name are printed on the same line. The space at the end of "Woof! I am " is part of the output: without it, the result would be Woof! I amRex.

    Details worth knowing

    • Methods belong to the object. An instance method always runs on a particular object, the one before the dot. Inside it, that object is available as this.
    • Printing is not returning. bark prints text and returns nothing. If you want the text itself, to store it or test it, write a method that returns a String instead, as describe does.
    • Methods can call each other. Inside the class, one method may call another by its bare name, such as bark();, and the call runs on the same object.
    • Several methods can share a name. Java allows methods with the same name if their parameter lists differ. This is called overloading.

    Common mistakes

    • Calling without parentheses. rex.bark; is not a call, and it doesn't compile as a statement. A call always needs ().
    • Calling on the class. Dog.bark(); fails because bark needs a particular dog to work on. Call it on a variable such as rex.
    • Forgetting the return type. A method header with no type, such as public bark(), is a compile error: the compiler reports that a return type is required.
    • Returning from a void method. return name; inside void bark() doesn't compile. Change the return type or remove the value.
    • Missing the return in a non-void method. A method declared to return a String must return on every path, or the compiler reports a missing return statement.
    • Wrong text. The output has to match exactly, including the exclamation mark and the space before the name.

    Key takeaways

    • A method is a function inside a class, and it defines what an object can do.
    • The header lists the access modifier, return type, name and parameters.
    • Inside an instance method, fields can be used by their bare names, and this.name means the same thing.
    • You call a method on an object with object.method(), and each object's own data is what the method sees.
    • void means no result, and any other return type needs a return statement with a matching value.
    Keep going with JavaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free