Java methods
modifiers
See java modifiers.
class MyClass{ public void punch_me(){}; private void punch_you(){}; protected void set_health(int health){}; }
constructor
Notice that the constructor has no return type.
class MyClass{ // constructor public MyClass(){ System.out.println('MyClass instantiated'); } }
destructor
Java does not have destructors . The best-practices seem to be implementing a
close()
ordispose()
method, and running it within a try/finally block.try { MyObj obj = new MyObj(); obj.do_something(); } finally { obj.close() }
overloading
Overloading is when a method is defined multiple times with different types of parameters. The function that is run is determined by the types of params passed to it.
class Car { public Car() {}; // constructor public Car(String name) {}; // overloaded constructor }
method references
The method-reference operator (
class::method
) allows you to pass methods as parameters.Under the hood, this is creating a
Function<T, R>
orConsumer<T>
(lambda expressions) and passing that as a parameter.
import java.util.function.Function; // takes 1 arg, produces result import java.util.function.Consumer; // takes 1 arg, no result import java.util.function.Supplier; // takes no arg, produces result class Printer { public static void static_print_name(String name) { System.out.println(name); } public void print_name(String name) { System.out.println(name); } } public class App { public static void main(String[] args) { // method-reference (static method) Consumer<String> static_print = Printer::static_print_name; static_print.accept("name"); // method-reference (instance method) Printer printer = new Printer(); Consumer<String> print = printer::print_name; print.accept("name"); } }See non-accepted answers in https://stackoverflow.com/questions/20001427/double-colon-operator-in-java-8
lambda functions
lambda functions allow you to bind quick/simple operations to a variable. That variable is a callable.
x -> x + x // single param, no check (x, y) -> x + y // without type check (int x, int y) -> x + x // with type check () -> 7 // no params, force return value