A method parameter changes how the method works, by
making a variable you can pass into it. You can make a parameter in the main
method and define the variable when declaring it to a body. A key aspect to remember
when defining a variable, is to make sure it is the same type as the parameter in
the method. When declaring two variables in a parameter use a comma. When referring
to the method put your variables in the same order as declared. When you define
the variable for the parameter you can either put it right into the open parenthesis,
or you can specify the variable before, and then put that variable into the
open parenthesis. Below is code showing three different methods all using
parameters to assign data to a body.
class Robot {
public void speak(String text) {
System.out.println(text);
}
public void jump(int height){
System.out.println("jumping:
" + height);
}
public void move(String direction, double distance){
System.out.println("moving
" + distance + "metres in direction" +direction);
}
}
public class App {
public static void main(String[] args){
Robot
sam = new Robot();
sam.speak("Hi I'm
Sam.");
sam.jump(7);
sam.move("west", 12.2);
String
greeting = "Hello
there. ";
sam.speak(greeting);
int value = 14;
sam.jump(value);
}
}
No comments:
Post a Comment