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:
publicmeans code outside the class may call the method;voidis the return type and means the method gives nothing back. A method that returns a value names that type here instead, such asintorString;barkis 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:
- Declare the method. Below the constructor, write
public void bark()with an empty body. It takes no parameters and returns nothing. - Fill in the body. Print
"Woof! I am "joined with thenamefield, usingSystem.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.
barkprints text and returns nothing. If you want the text itself, to store it or test it, write a method that returns aStringinstead, asdescribedoes. - 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 becausebarkneeds a particular dog to work on. Call it on a variable such asrex. - 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
voidmethod.return name;insidevoid 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
Stringmust 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.namemeans the same thing. - You call a method on an object with
object.method(), and each object's own data is what the method sees. voidmeans no result, and any other return type needs areturnstatement with a matching value.