티스토리 뷰




Overloading in Java 


In Java, If two or more methods in a class have the same method name but different parametersthe methods are defined as different methods even though it has the same method name. 




simple example code

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
class Calculator {
    int a, b, c;
 
    public void setCal(int a, int b){
        this.a = a;
        this.b = b;
    }
    //same method name with different parameters
    public void setCal(int a, int b, int c){
        this.a = a;
        this.b = b;
        this.c = c;
    }
   
    public void sum() {
        System.out.println(this.a + this.b + this.c);
    }
    
    public void avg() {
        System.out.println((this.a + this.b + this.c) /3);
    }
}
 
public class CalculatorConstructorDemo5 {
    public static void main(String[] args) {
        Calculator cal = new Calculator();
        cal.setCal(10,30);
        cal.sum();
        cal.avg();
        cal.setCal(10,30,15);
        cal.sum();
        cal.avg();
    }
}
cs



Result

40

13

55

18




'JAVA' 카테고리의 다른 글

Java Generics (runtime error,compile error)  (0) 2019.01.06
static in Java  (0) 2019.01.05
Overriding in Java with an simple code  (0) 2019.01.04
super keyword  (0) 2019.01.03
Inheritance  (0) 2019.01.03