-1

Is it possible to use functions in Java? I'm not used to OOP and I like having global functions that can be used in any classes. Is this possible in Java? Right now, I have a class named $ that contains all my functions (as static methods). Is there a Java convention for using classes like this? (I borrowed the $ from JQuery)

Leo Jiang
  • 24,497
  • 49
  • 154
  • 284
  • 1
    See [this question](http://stackoverflow.com/questions/19529603/any-risk-using-a-single-dollar-sign-as-a-java-class-name). – rgettman Feb 05 '14 at 18:48
  • 1
    you can use static import and use functions without any prefix in any class http://viralpatel.net/blogs/static-import-java-example-tutorial/ – jbaliuka Feb 05 '14 at 18:51
  • 2
    Don't use Java if you intend to code as if you were using JavaScript. Use JavaScript instead. – JB Nizet Feb 05 '14 at 18:51
  • 2
    JavaScript is also object oriented and it is as useless as Java if you do not want to learn something new :) – jbaliuka Feb 05 '14 at 18:56

2 Answers2

0

You can write static class methods with no state, which is effectively a pure function. You can do a "static import" so you don't have to reference the enclosing class. However all your methods/functions must be defined in a class. So, yes, you can do those things, but the syntax isn't perfect.

user2684301
  • 2,550
  • 1
  • 24
  • 33
0

Java encapsulates everything in classes. You must have all functions within a class. You can either have one big class with many functions and program your Java program more or less like you are writing C or have static functions/class method.

For instance you can have a class Gloabls where you put all your functions:

class Globals {
    public static int AddNumbers(int a, int b) { return a+b; }
}

class MyClass {
    public MyClass { int four = Globals.AddNumbers(1,3); }
    public static void main(String[] args) { new MyClass(); }
}
Aquaplanet
  • 563
  • 4
  • 14