Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

no ordinary "function" in java?

Tags:

java

in php you can declare a function in a global scope with function.

is this not possible in java? looks like every function is in a class as a method. so everything is OOP in java? no procedural code?

like image 852
ajsie Avatar asked Jan 09 '10 01:01

ajsie


4 Answers

The closest thing you can have to a "free-floating" function is a static function, which you can call as qualified with the class name, e.g.

public class Foo {
   public static void bar(){}
}

... elsewhere

Foo.bar();

You can add a bit of syntactic sugar to this to make it look like what you're thinking of:

import static Foo.bar;

... elsewhere

bar();
like image 110
Steve B. Avatar answered Sep 19 '22 13:09

Steve B.


Yep. But you can define static methods, which ultimately can act as methods contained within a class but be invoked without instantiating an instance of the class. That is, if you define a method bar as static in class Foo then it may be invoked as Foo.bar().

like image 25
Mark Elliot Avatar answered Sep 23 '22 13:09

Mark Elliot


That's right, no procedural code, everything's an object defined by a class (except the few primitive data types). You can, however, use static methods:

public class MyClass {
    public static void callMe() {
        System.out.println("HEY");
    }
}

public class MyOtherClass {
    public void someMethod() {
        MyClass.callMe();
    }
}

The JVM-based language Scala does allow you to create higher-order functions, which you can pass around as values.

like image 40
Kaleb Brasee Avatar answered Sep 20 '22 13:09

Kaleb Brasee


Oh yes, OO indeed. You can code pseudo procedural stuff within a static method though.

like image 28
o.k.w Avatar answered Sep 19 '22 13:09

o.k.w