Java
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.
Exercise 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.
Show example solution
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();
}
}
Test yourself
-
What does void mean in a method definition?
- The method returns no value
- The method returns a string
- The method is hidden
- The method is static
Show answer
The method returns no value — The void return type means the method returns no value.
-
Complete the method call
class Greeter {
void greet() {
System.out.println("Merhaba");
}
public static void main(String[] args) {
Greeter g = new Greeter();
g____;
}
}
Show answer
class Greeter {
void greet() {
System.out.println("Merhaba");
}
public static void main(String[] args) {
Greeter g = new Greeter();
g.greet();
}
}
-
Match the method parts
- void
- Return type
- greet
- Method name
- ()
- Parameter list
- { }
- Body
Next lesson: new