AP Computer Science A
3 min read•Last Updated on July 11, 2024
Milo Chang
Milo Chang
Look at this chunk of code: 💻
public class Cats
{
public int countNumFeet (int numCats)
{
return 4*numCats;
}
// There may be instance variables, constructors, and other methods not
// shown.
}
Can you identify the method header? 🤔
That's right! 👏 It's "public int countNumFeet (int numCats)"! 🐱
Breaking it Down: 🔍
The keyword "public" means that this method can be accessed from other classes.
private int countNumFeet (int numCats)
Putting "private" means that the method can only be accessed within the "Cats" class The keyword "int" tells you what this method returns when it is called.
In this case, it returns an integer value after it is called
It can be replaced by "double", "boolean", "String", or the name of a class if the method returns an object
If the word "void" is there instead of the other options, this means the method doesn't return anything The word "countNumFeet" is the name of the method.
This can be replaced with anything without changing what the method does
It's best if you make the name of the method something that lets people easily know what it's doing The "int numCats" tells you what is being passed into this method.
In the example, an integer called "numCats" is being passed in
You can have a method that has nothing being passed in:
public int countNumFeet ()
public int countNumFeet (int numCats, int numEars, boolean isAngry)
Method headings may also include the phrases "static" or "abstract", but this will be discussed in later articles.
Try it out! 😃
Answers: ✔
# 1) private void example1 (String text)
# 2) public boolean example2 ()
# 3) public String example3 (boolean testPassed, int score)
Summary: 🎉✨
You can write a method header with just a few simple steps.
That's it! You're ready to start writing your own method headers! 👏