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?
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();
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()
.
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.
Oh yes, OO indeed. You can code pseudo procedural stuff within a static method though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With