JAVA - 다형성

choko's avatar
Jun 28, 2024
JAVA - 다형성
Contents
다형성
 
 

다형성

  • 객체지향에서 다형성이란, 프로그램 언어 각 요소들이 다양한 자료형에 속하는 것이 허가되는 성질을 가리킨다.
  • 다형성을 구현하는 방법에는 오버로딩, 오버라이딩, 함수형 인터페이스가 있다.
 
 

오버로딩

  • 함수의 매개변수에, 여러 개의 메소드를 정의할 수 있는 것.
    • println()에 boolean, char, int 모두 호출할 수 있다.
    • public class PrintStream { ... public void println() { this.newLine(); } public void println(boolean x) { synchronized(this) { this.print(x); this.newLine(); } } public void println(char x) { synchronized(this) { this.print(x); this.newLine(); } } public void println(int x) { synchronized(this) { this.print(x); this.newLine(); } } ... }
 
 

오버라이딩

  • 상위 클래스의 메서드를 하위 클래스에서 재정의하는것
  • 상속받는 메서드를 재정의한다.
    • public abstract class Figure { protected int dot; protected int area; public Figure(final int dot, final int area) { this.dot = dot; this.area = area; } public abstract void display(); // getter } public class Triangle extends Figure { public Triangle(final int dot, final int area) { super(dot, area); } @Override public void display() { System.out.printf("넓이가 %d인 삼각형입니다.", area); } }
    • Triangle이 Figure을 상속하며, display() 메서드를 오버라이딩했다.
    •  
       
 

함수형 인터페이스

  • 추상 메서드가 1개만 정의된 인터페이스를 통칭하여 일컫는다.
  • 람다 표현식을 이용해 함수형 프로그래밍을 구현하기 위해 사용한다.
 
import java.util.function.BiFunction; ... public enum Operator { PLUS("+", (a, b) -> a + b), MINUS("-", (a, b) -> a - b), MULTIPLY("*", (a, b) -> a * b), DIVIDE("/", (a, b) -> a / b); private final String sign; private final BiFunction<Long, Long, Long> bi; Operator(String sign, BiFunction<Long, Long, Long> bi) { this.sign = sign; this.bi = bi; } public static long calculate(long a, long b, String sign) { StudyApplication.Operator operator = Arrays.stream(values()) .filter(v -> v.sign.equals(sign)) .findFirst() .orElseThrow(IllegalArgumentException::new); return operator.bi.apply(a, b); } } public static void main(String[] args) { System.out.println(Operator.calculate(10l, 15l, "+")); // 25 System.out.println(Operator.calculate(10l, 15l, "*")); // 150 }
 
  • BiFunction
    • 함수형 프로그래밍을 구현하기 위해 Java 버전 1.8부터 도입된 함수형 인터페이스
    • 아래 함수형 인터페이스 표준 API의 Function<T, R>의 매개변수가 2개인 것이 BiFunction이다.
 

함수형 인터페이스 표준 API

  • 함수형 인터페이스의 매개변수/리턴 타입의 개수가 달라질 수 있는데, 이러한 형태를 일일히 정의해서 사용하기엔 너무 양이 많으니, 자바 개발자들이 미리 함수형 인터페이슬르 만들어 제공해 두었다.
  • 강타입 언어인 자바에서, 람다 함수에서 타입을 지정해주기 위해 표준화된 인터페이스라고 생각하면 된다.
 
  • 종류
    • Runnable : 매개 변수 사용 x, 리턴 x
      • void run() 형태
    • Consumer<T> : 매개 변수 o, 리턴 x
      • void accept(T t> 형태
    • Supplier<T> : 매개 변수 사용 x, 리턴 o
      • T get() 형태
    • Function<T, R> : 매개값을 매핑(타입변환)해서 리턴하기
      • R apply(T t) 형태
    • Predicate<T> : 매개값이 조건에 맞는지 단정해서 boolean 리턴
      • boolean test(T t) 형태
    • Operator : 매개값을 연산해서 결과 리턴
      • R applyAs(T t) 형태
 
Share article

Tom의 TIL 정리방