JAVA
Overloading in Java with simple example
seoca
2019. 1. 4. 11:03
Overloading in Java
In Java, If two or more methods in a class have the same method name but different parameters, the 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