Learn Java Basics
About Lesson

There are four types of functions:

  1. Static Functions: These are functions that belong to a class and can be called without creating an instance of that class.

Example:

public class Calculator {
public static int add(int x, int y) {
return x + y;
}
}

You can call this function using Calculator.add(2, 3).

  1. Non-Static Functions: These are functions that belong to an instance of a class and can only be called on an object of that class.

Example:

public class Person {
public void sayHello() {
System.out.println("Hello!");
}
}

You can call this function using Person person = new Person(); person.sayHello();.

  1. Getter Functions: These are functions that are used to get the value of a private variable in a class.

Example:

public class Person {
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

You can call the getter function using Person person = new Person(); String name = person.getName();.

  1. Setter Functions: These are functions that are used to set the value of a private variable in a class.

Example:

public class Person {
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

You can call the setter function using Person person = new Person(); person.setName("John");.

  1. Recursive Functions: These are functions that call themselves in order to solve a problem.

Example:

public class Factorial {
public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
}

You can call this function using Factorial.factorial(5) to get the factorial of 5.

These are just a few examples of the types of functions in Java. There are many more, including constructors, overloaded functions, and abstract functions.

Join the conversation