Junior — Middle
How to declare and implement an inner function inside a class in Java?
sobes.tech AI
Answer from AI
In Java, you can declare an inner class within a class, which will have access to the fields and methods of the outer class. If you're talking about an "inner function," Java doesn't have functions as such outside of methods, but you can use inner classes or lambda expressions.
Example of an inner class with a method:
public class OuterClass {
private int value = 10;
class InnerClass {
void printValue() {
System.out.println("Value from outer class: " + value);
}
}
void createInner() {
InnerClass inner = new InnerClass();
inner.printValue();
}
}
In Android and Java 8+, you can use lambda expressions to declare functions inside methods:
public void example() {
Runnable runnable = () -> System.out.println("Inner function via lambda");
runnable.run();
}