Skip to content

Methods

How to make a function that can be used again

  • Lesson
  • 3 min read
  • 3 of 9 in this chapter

What are methods?

Methods are functions that can be used over and over again. Think of it as an action that an object/class does. These functions can be used over and over again instead of writing code. Earlier we learned about .Math functions. All of these functions are part of a .Math class in Java. Lets create a method in the class ‘Cat’’...

Java
//this is how we declare a method
class Cat{
 //these are attributes
 String name = "Garfield";
 String color = "orange";
 String type = "tabby";
 int age = 40;
 //this is a method
 void makesound(){
 System.out.println("Meow");
 }
}
public class MyFirstClass {
 public static void main(String[] args) {
 Cat garfield = new Cat();//this is how we create an object
 garfield.makesound();//this is how we execute a method
 }
}

Parameters for methods

Parameters are a way to pass information into a specific method. The information or data passed into a method can then be used for different parts of code in a function. For example, this is how we pass information into a method…

Java
void add(int a,int b){
 System.out.println(a+b);
 //this method adds an integer 'a' with another integer 'b'
}//this is how we would instantiate a parameter.

This is how we call the method with a parameter

Java
objectname.add(5+6);
//the output would be 11

Method Overloading

We can do something called method overloading. This is where we have multiple functions with the same name but different parameters. This is useful for writing clean code, and having multiple methods that execute the same function with different parameters. For example...

Java
void add(int a,int b){
 System.out.println(a+b);
}
void add(int a, int b, int c){
 System.out.println(a+b+c);
}
/*in both of the above methods we are adding, yet in one we are adding 2 variables and in the other we are adding 3 variables*/

In the main method we would put this...

Java
objectname.add(5+5+5);//result is 15
objectname.add(5+5);//result is 10

Methods that return data

These are methods in which the end result returns a data type. These methods can be used to determine a value of a variable through a set of code. For example this is how we would use such a method...

Java
public class Methodsexample {
 int thefunction(){
 int variablename = 1;
 return variablename;
/*the return command returns data to the method in the form of an int datatype(in this example).*/ 
}
public static void main(String[] args) {
 Methodexample example = new Methodexample();
 System.out.println(example.thefunction()); //this prints out '1'
 int aVariable = example.thefunction(); 
 /*the way that we utilize the method is just like any other datatype 
 but with a "()" after the method name*/ 
}
}