Method overloading occurs when a class has multiple methods with the same name,
but the methods are declared with different parameters.
So you can execute a method with one name, but call it with different arguments.
Java can resolve which method it needs to execute, based on the arguments being passed, when the method is invoked.
A method signature consists of the name of the method, and the uniqueness of the declaration of its parameters
In other words, a signature is unique, not just by the method name,
but in combination with ther number of parameters, their types,
and the order in which they are declared
메서드 오버라이딩은 클래스가 여러개의 동일한 이름의 매서드를 가지고 있을때 각 메서드마다 갖는 동일하지 않은 파라미터로 메서드를 정의하는 기법이다.
자바는 여러개의 동일한 이름의 메서드가 한 클래스에 존재하더라도, 메서드가 받는 arguments에 따라 어떤 메서드가 실행되어야하는지 알 수 있다.
메서드 시그니처는 메서드의 이름과 그 메서드가 받는 고유한 파라미터로 정의되어 진다.
즉, 시그니처는 해당 메서드의 고유한 메서드명과 받는 파라미터를 뜻한다.
메서드 시그니처는 메서드의 이름과 파라미터의 개수로 정의될 뿐만 아니라, 해당 파라미터의 타입과 파라미터 주입 순서에 따라서도 고유의 시그니처를 갖는다.
다만 해당 메서드가 반환하는 값과, 매개변수의 이름은 시그니처의 조건에 해당하지 않는다.
public static void doSomething(int paramA) {
}
public static void doSomething(int paramB) {
}
public static int doSomething(int paramA) {
return 1;
}
위 예시는 모두 잘못된 메서드 시그니처이다.
파라미터의 이름이 다르다고하여 시그니처가 될 수 없으며
리턴 타입이 다르다고하여 시그니처가 될 수 없다.
public class Main {
public static void main(String[] args){
calcPoint("Timm", 1000);
calcPoint(20000);
calcPoint(20000,"MS");
}
public static void calcPoint(String playerName, int score) {
System.out.println("Player: " + playerName + " score: " + score);
}
public static int calcPoint(int score) {
System.out.println("some Player broke old Record: " + score * 100000);
return score * 1000;
}
public static void calcPoint(int score, String playerName){
int point = calcPoint(score);
System.out.println("Winner is " + playerName + "! point is: " + point);
}
}
---output---
Player: Timm score: 1000
some Player broke old Record: 2000000000
some Player broke old Record: 2000000000
Winner is MS! point is: 20000000
매개변수의 순서가 다르고, 개수가 다르다면 자바는 메서드 시그니처의 조건을 충족하였기 때문에 동일한 메서드명의 메서드가 반환값이 다르더라도 에러 없이 처리됨을 볼 수 있다.
또한 3번째 메서드 내부 함수에서 값으로 사용된 2번째 메서드가 정상적으로 작동함을 확인할 수 있다.
원의 너비와 직사각형의 너비를 오버로딩 메서드로 구현
public static void main(String[] args){
final double circle = area(10);
final double ractangle = area(24, 18);
System.out.println(circle + ractangle);
}
public static double area(double radius) {
return radius < 0 ? -1.0 : radius * radius * Math.PI;
}
public static double area(double x, double y) {
return (x < 0 || y < 0) ? -1.0 : x * y;
}
---output---
746.1592653589794