Java/Methods: Difference between revisions
From charlesreid1
(Created page with "Basic idea of methods: procedural decomposition, separating parts of the task, making code more reusable ==Lambda Expressions== {{Main|Java/Lambdas}} When it comes to dea...") |
No edit summary |
||
| Line 1: | Line 1: | ||
Basic idea of methods: procedural decomposition, separating parts of the task, making code more reusable | 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 [https://stackoverflow.com/questions/2186931/java-pass-method-as-parameter#2186993 stack overflow]: | |||
<pre> | |||
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"); | |||
} | |||
} | |||
</pre> | |||
==Lambda Expressions== | ==Lambda Expressions== | ||
Revision as of 22:27, 5 July 2017
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