CodeBlanks Logo Icon CodeBlanks

Methods

Learn methods and this inside a class.

Methods

A method is a code block that defines a class's behavior. A method has a name, a parameter list, a return type and a body. The body sits between curly braces.

Example: void greet() { System.out.println("Hello"); }. Here void is the return type (returns nothing), greet is the method name, empty parentheses mean no parameters. A method is defined once and called on an instance as object.method(). Parameterized methods take values in parentheses.

The this keyword

Inside a method body, this refers to the instance on which the method was called. It is used to distinguish a field from a parameter with the same name. When a parameter shadows a field, this.field accesses the instance's field.

Example: void setName(String name) { this.name = name; }. Here the parameter name and the field name share the same name. this.name means the instance's field, name means the parameter. Without this, the assignment would target the parameter itself; the field would not change.

Practice Add a method to the Greeter class

Define a class named Greeter. Add a String name field and a void greet() method. In the method body write System.out.println("Hello " + name);. In main create a Greeter instance, assign a value to name and call the greet method.

Starter code

Main.java
// Define the Greeter class
// Add a String name field and a greet method
// Instantiate and call greet in main

Sample solution

Main.java
class Greeter {
    String name;
    void greet() {
        System.out.println("Hello " + name);
    }
    public static void main(String[] args) {
        Greeter g = new Greeter();
        g.name = "World";
        g.greet();
    }
}

Expected output

Hello World

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does void mean in a method definition?

  • The method returns no value Correct answer
  • The method returns a string
  • The method is hidden
  • The method is static

Explanation: The void return type means the method returns no value.

2 Complete the method call

Question
class Greeter {
    void greet() {
        System.out.println("Merhaba");
    }
    public static void main(String[] args) {
        Greeter g = new Greeter();
        g____;
    }
}
Answer
class Greeter {
    void greet() {
        System.out.println("Merhaba");
    }
    public static void main(String[] args) {
        Greeter g = new Greeter();
        g.greet();
    }
}

Explanation: The method is called with .greet() on the instance.

3 Match the method parts

Term Meaning
void Return type
greet Method name
() Parameter list
{ } Body

All lessons in Intermediate