There is no usual "function" in java?

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

Is this impossible in java? It looks like every function is in the class as a method. so what is all oop in java? no procedural code?

+5
source share
10 answers

The closest thing you can use for a "free-floating" function is a static function, which you can call qualified with a class name, for example.

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

... in the other place

Foo.bar();

You can add a little syntactic sugar to this to make it look what you think:

import static Foo.bar;

... in the other place

bar();
+18
source

. , , , . , bar static Foo, Foo.bar().

+3

, , , ( ). :

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

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

, JVM Scala, , .

+3

, OO . .

+3

public class MyClass{
   public static void m(){
      ...
   }
}


MyClass.m();
+3

, , , , , , " ". , , - java.lang.Math, . "Util" , , .

+3

, . Java .

+1

java- , , . OO =)

0

. , .

-1

All Articles