Junior — Middle
Is it possible to define a function outside the body of a class in an object-oriented programming language?
sobes.tech AI
Answer from AI
In Java, all methods must be defined within the body of a class or interface. You cannot declare a function outside of a class, as is possible in languages like C++ or JavaScript. Even static methods are part of a class. If you need to define a function that is not related to the state of an object, you declare it as a static method inside a class:
public class Utils {
public static int sum(int a, int b) {
return a + b;
}
}
Thus, in Java, functions outside of classes do not exist; all methods belong to classes.