#Why are Interfaces used?

1 messages ยท Page 1 of 1 (latest)

proven geyserBOT
#

<@&987246399047479336> please have a look, thanks.

#

While you are waiting for getting help, here are some tips to improve your experience:

Code is much easier to read if posted with syntax highlighting and proper formatting.

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.

wintry oxide
#

Ok that was a bad example

#

But say I needed to use them in multiple java files

#

What does "achieving abstraction" mean?

proven geyserBOT
#

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:

  1. Create a class that implements the interface, like Player
  2. 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
  1. 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
cunning marsh
#

if sth is still unclear after reading that, just ask ๐Ÿ™‚

wintry oxide
#

ohhhh

#

Im so happy

#

thank you

wintry oxide
#

:: double colon

#

Is there a nice message for that that TJ-Bot has?

cunning marsh
wintry oxide
#

Oh wait nvm

#

Ok, I have understood everything