<< Hide Menu
2 min readβ’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)
The keyword "int" tells you what this method returns when it is called.
The word "countNumFeet" is the name of the method.
The "int numCats" tells you what is being passed into this method.
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! π
#1) Write the header for a method that can only be accessed within the class it's declared in. This method takes in a String called "text" and doesn't return anything. Call your method "example1". Β (Scroll down for the answer)
#2) Write the header for a method that can be accessed from other classes. This method takes nothing in and returns a boolean. Call your method "example2". (Scroll down for the answer)
#3) Write the header for a method that can be accessed from other classes. This method takes in a boolean "testPassed" and an integer "score". It returns a String. Call your method "example3". (Scroll down for the answer)
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! π
Β© 2024 Fiveable Inc. All rights reserved.