开发者

no ordinary "function" in java?

开发者 https://www.devze.com 2022-12-15 18:09 出处:网络
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 j开发者_如何学Goava? no p

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 j开发者_如何学Goava? 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.


You can make a method static an call it without creating an Object

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


MyClass.m();


Expanding on what everyone else is saying, if you have a lot of such functions, it is common to group them together in classes that are full of nothing but static methods, often called "utility classes." The first example that comes to mind is java.lang.Math but there are tons of others. Any class with "Util" in its name is likely to follow this pattern.


Yes, that is correct. Java is strictly OOP.


In java world, all functions must be declared within a class, no matter what. Welcome to OO world =)


Yes, you can make static functions, er, methods, but then you have to hard-code calls to them. To select a callback at runtime, you have to make an interface (not a function pointer, procedural type, or delegate), and then make a bogus class (though perhaps anonymous) to "implement" it. Enjoy the make-work!

Or, enjoy the humorous satirazation: http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html


Do not jive well well OOP. You can still have define a public static method and call it from anywhere as others have mentioned.

0

精彩评论

暂无评论...
验证码 换一张
取 消