티스토리 뷰

728x90

오버로딩을 할 때 Method Signature가 중요하다.

Method Signature가 같다는 것은 name 과 parameter types가 같다는 것을 말한다.

메서드 시그니처에는 return type(리턴 타입)은 포함되지 않는다.

 

시그니처가 같은 메서드는 동시에 한 클래스안에서 정의할 수 없다. 

시그니처가 다른 메서드는 오버로딩이 가능하다. 이름이 다르거나 파라미터의 타입이나 개수가 다르거나..

public class MethodSignature {
    public static void main(String[] args) {

    }

    public String hello(int i) {return "";}

    public String hello(String s) {return "";}
}

hello 메서드를 보면 이름은 같지만 파라미터의 타입 (위에는 int, 아래는 String) 이 달라서 시그니처가 다르기 때문에 오버로딩이 가능하다. 자바는 시그니처를 이름과 메서드 파라미터와 개수로 판단한다.

그런데 리턴타입이 포함된다고 한다면 아래도 오버로딩이 성립해야 되는데 그렇지 않다.

public class MethodSignature {
    public static void main(String[] args) {

    }

    public String hello(int i) {return "";}

    public List hello(int i) {return null;}
}

메서드 시그니처에 리턴타입이 포함된다고 하면 위 코드가 오버로딩이 되어야 하는데 시그니처가 같기 때문에 (이름과 파라미터 타입) 컴파일 오류가 난다.

고로 메서드 시그니처에는 리턴타입이 포함되지 않는다.

 

Method Type(메서드 타입)은 메서드 시그니처와 다르게 이름이 포함되지 않는다.

return type, method type parameter, method argumet types, exception 를 묶어서 메서드 타입이라고 한다.

메서드 타입이 일치하면 Method Type(메서드 타입) 이 일치하면 람다에서 메서드 레퍼런스를 사용할 수 있다.

public class MethodType {
    public static void main(String[] args) {

        List<Integer> numbers = List.of(1, 2, 3, 4, 5);
        numbers.forEach(System.out::println);
    }
}

간단하게 리스트를 만들어서 forEach에 System.out.println을 메서드 레퍼런스로 넘겼다. forEach는 Consumer 람다를 받는데 

Consumer는 입력 값을 받고 반환값은 없는 accept 메서드를 갖는다. println을 메서드 레퍼런스로 넘길 수 있었던 이유는 메서드 타입이 같기 때문에 메서드 레퍼런스를 사용할 수 있다.

//java.io.PrintStream
public void println(Object x) {
    String s = String.valueOf(x);
    synchronized (this) {
        print(s);
        newLine();
    }
}

 

추가

메소드 시그니처 좋은 이미지와 글 있어서 첨부

https://stackoverflow.com/questions/16149285/does-a-methods-signature-in-java-include-its-return-type

 

Does a method's signature in Java include its return type?

Does the method signature in a Java class/interface include its return type? Example: Does Java know the difference between those two methods: public class Foo { public int myMethod(int par...

stackoverflow.com

출처

https://www.youtube.com/watch?v=s-tXAHub6vg&list=PLv-xDnFD-nnmof-yoZQN8Fs2kVljIuFyC&index=16&ab_channel=TobyLee 

 

 

728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함