#Why are Interfaces used?
1 messages ยท Page 1 of 1 (latest)
While you are waiting for getting help, here are some tips to improve your experience:
If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.
Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.
Ok that was a bad example
But say I needed to use them in multiple java files
What does "achieving abstraction" mean?
An interface defines a set of method signatures, as contract. It can greatly increase code modularity. Often, interfaces are property-driven.
interface CanWalk {
void walkLeft();
void walkRight();
}
There is no method body. So if a class implements CanWalk, he makes the promise to offer those methods:
class Player implements CanWalk {
int x;
@Override
void walkLeft() {
x--;
}
@Override
void walkRight() {
x++;
}
}
Someone could now demand a CanWalk instance and use the methods:
class Mover {
static void moveAround(CanWalk canWalk) {
for (int i = 0; i < 10; i++) {
canWalk.walkRight();
}
canWalk.walkLeft();
canWalk.walkRight();
}
}
Note that the moveAround accepts everything that can walk.
Mover.moveAround(player);
We could also give it a Dog, as long as it implements CanWalk.
You have two options to create instances of interfaces:
- Create a class that
implementsthe interface, likePlayer - Use an anonymous class:
CanWalk canWalk = new CanWalk() {
@Override
void walkLeft() {
System.out.println("Walking left");
}
@Override
void walkRight() {
System.out.println("Walking right");
}
};
An interface that only offers one method is called a functional interface:
@FunctionalInterface
interface IntOperation {
int operate(int a, int b);
}
You have two additional options to create instances of it:
3. Lambda expression
IntOperation operation = (a, b) -> a * b;
System.out.println(operation.operate(5, 3)); // Prints 15
- Method reference
// Method in MathUtil
static int multiply(int a, int b) {
return a * b;
}
// Use it as
IntOperation operation = MathUtil::multiply;
System.out.println(operation.operate(5, 3)); // Prints 15
if sth is still unclear after reading that, just ask ๐
wait...
I understand now...
ohhhh
Im so happy
thank you
Well, there is one thing
:: double colon
Is there a nice message for that that TJ-Bot has?
method references? whats unclear about them?