본문 바로가기

카테고리 없음

[JAVA] 오버로딩(overloading) 예제

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 a;
 
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(1020);
        c1.sum();       
        c1.avg();
        c1.setOprands(102030);
        c1.sum();       
        c1.avg();
         
    }
  
}
cs