From charlesreid1

Basic idea of methods: procedural decomposition, separating parts of the task, making code more reusable

Methods as Objects

To wrap a method in an object that can be passed around, have a state, etc., you can use the "Command" design pattern, in which you encapsulate a single action in an object that contains all information and materials necessary to execute that command.

An example from stack overflow:

public class CommandExample {
    public interface Command {
        public void execute(Object data);
    }

    public class PrintCommand implements Command {
        public void execute(Object data) {
            System.out.println(data.toString());
        }    
    }

    public static void callCommand(Command command, Object data) {
        command.execute(data);
    }

    public static void main(String... args) {
        callCommand(new PrintCommand(), "hello world");
    }
}

Lambda Expressions

When it comes to dealing with functions as first-class objects in the language, Java is much more limited than Python. In fact, it was not until Java 8 that Java finally got lambda expressions, which are ways of defining functions using in-place, shorthand expressions.

Here is the Java tutorial on Lambda expressions: http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html


Flags





See also: