[死亡経路2週目-3]TIL
JAVA
Interface
インタフェース機能
interface MyRunnable {
void myRun();
}
interface YourRunnable {
void yourRun();
}
public class Main implements MyRunnable, YourRunnable {
public static void main(String[] args) {
Main m = new Main();
m.myRun();
m.yourRun();
MyRunnable myRunnable = new Main();
myRunnable.myRun();
YourRunnable yourRunnable = new Main();
yourRunnable.yourRun();
}
@Override
public void myRun() {
System.out.println("Hello myRun!");
}
@Override
public void yourRun() {
System.out.println("Hello yourRun!");
}
}
結合度の低減(ログインインタフェースがあれば/NAVER、KACAログインインプリメンテーション)
依存の具体化
抽象に依存する場合
defaultメソッド機能
interface MyInterface { // 추상메서드로만 이뤄진 클래스 == 인터페이스
// 구현이 있다.
// 추상메서드가 아니라는 얘기는 인터페이스 안에 구현체가 들어간다.
default void sayHello() {
System.out.println("Hello World");
}
void method(); // 구현이 X
}
public class Main implements MyInterface{
public static void main(String[] args) {
Main m = new Main();
m.sayHello();
}
// 물론 오버라이드도 가능하다.
@Override
public void sayHello() {
System.out.println("Bye World");
}
@Override
public void method() {
throw new RuntimeException();
}
}
Functional Interface
@FunctionalInterface
interface MyMap {
void map();
default void sayHello() {
System.out.println("SayHello");
}
static void sayBye() {
System.out.println("ByeHello");
}
}
抽象的な方法が1つしかないインタフェース:一時的なインタフェースの作成
Lambda式
public class Main2 {
public static void main(String[] args) {
// 익명 클래스 사용
new MyRunnable() {
@Override
public void run() {
System.out.println("hello");
}
}.run();
// 익명메서드를 사용해서 표현하는 방식 : 람다 표현식
// 생략할 수 있게 만들어준다 어차피 오버라이드를 해줄것이기 때문이다.
// 함수형 인터페이스라면 어차피 메서드는 하나이기 때문에
MyRunnable myRunnable = () -> System.out.println("hello");
}
}
MyMapper m = (str) -> str.length();
MyConsumer c = i -> System.out.println(i);
方法の研究
MyMapper m = String::length;
MyConsumer c = System.out::println;
Reference
この問題について([死亡経路2週目-3]TIL), 我々は、より多くの情報をここで見つけました https://velog.io/@gudnr1451/데브코스-2주차-3-TILテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol