Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 제5인격
- counldn't have
- 명세기반테스트
- 명절 표현
- UE4
- I'm glad
- relif
- html
- by any chance
- if조건절
- by until
- metascore
- continue to
- 형변환
- sort함수
- end up ing
- it's a good thing
- 변수
- might have p.p
- gameQA
- ISTQB
- java
- happen to
- Realtime Rendering
- C++
- for ing
- 코로나19
- know
- 게임QA
- keep -ing
Archives
- Today
- Total
Records rather than Memories
overloading 본문
서로 다른 매개 변수의 형식을 가지는 메소드를 여러개 정의할 수 있는 방법이 overloading이다.
만약 3개의 값을 대상으로 연산을 하고 싶다면?
1
|
c1.setOprands(10, 20, 30);
|
cs |
다음과 같이 3개의 값을 받아야 하기 때문에 setOprand 메소드와 연산 메소드를 수정하면 된다.
1
2
3
4
5
|
public void setOprands(int left, int right, int third){
this.left = left;
this.right = right;
this.third = third;
}
|
cs |
그런데 이렇게 하면 입력값 수가 달라질 때마다 다른 이름의 메소드(setOprand2, setOprand3...)를 작성해야한다.
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
32
33
34
35
36
37
38
39
40
41
42
43
|
package org.opentutorials.javatutorials.overloading.example1;
class Calculator{
int left, right;
int third = 0;
public void setOprands(int left, int right){
System.out.println("setOprands(int left, int right)");
this.left = left;
this.right = right;
}
public void setOprands(int left, int right, int third){
System.out.println("setOprands(int left, int right, int third)");
this.left = left;
this.right = right;
this.third = third;
}
public void sum(){
System.out.println(this.left+this.right+this.third);
}
public void avg(){
System.out.println((this.left+this.right+this.third)/3);
}
}
public class CalculatorDemo {
public static void main(String[] args) {
Calculator c1 = new Calculator();
c1.setOprands(10, 20);
c1.sum();
c1.avg();
c1.setOprands(10, 20, 30);
c1.sum();
c1.avg();
}
}
|
cs |
위의 예제를 보면 setOprand의 이름이 같음에도 다른 매개변수, 숫자, 타입에 의해 오버로딩이 이루어진다.
즉, 서로 다른 메소드로 인식하게 된다.
'Software > JAVA' 카테고리의 다른 글
접근 제어자 (0) | 2019.10.23 |
---|---|
패키지 (0) | 2019.10.22 |
overriding (0) | 2019.10.21 |
자바에서 상속이란 무엇인가 (0) | 2019.10.21 |
[java] 초기화와 생성자 (0) | 2019.10.21 |
Comments