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.setOprands(left, 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();
}
}
실행결과
setOprands(int left, int right)
30
15
setOprands(int left, int right, int third)
60
30
리턴타입이 다르면 오류가 발생한다.
public class OverloadingDemo {
void A (){System.out.println("void A()");}
void A (int arg1){System.out.println("void A (int arg1)");}
void A (String arg1){System.out.println("void A (String arg1)");}
//int A (){System.out.println("void A()");} // 오류
public static void main(String[] args) {
OverloadingDemo od = new OverloadingDemo();
od.A();
od.A(1);
od.A("coding everybody");
}
}
public class OverloadingDemo2 extends OverloadingDemo{
void A (String arg1, String arg2){System.out.println("sub class : void A (String arg1, String arg2)");}
void A (){System.out.println("sub class : void A ()");}
public static void main(String[] args) {
OverloadingDemo2 od = new OverloadingDemo2();
od.A();
od.A(1);
od.A("coding everybody");
od.A("coding everybody", "coding everybody");
}
}
실행 결과: 상속한 부모 클래스 거도 오버로딩 가능!
sub class : void A ()
void A (int arg1)
void A (String arg1)
sub class : void A (String arg1, String arg2)
package org.opentutorials.javatutorials.overloading.example1;
class Calculator{
int[] oprands;
public void setOprands(int[] oprands){
this.oprands = oprands;
}
public void sum(){
int total = 0;
for(int value : this.oprands){
total += value;
}
System.out.println(total);
}
public void avg(){
int total = 0;
for(int value : this.oprands){
total += value;
}
System.out.println(total/this.oprands.length);
}
}
public class CalculatorDemo {
public static void main(String[] args) {
Calculator c1 = new Calculator();
c1.setOprands(new int[]{10,20});
c1.sum();
c1.avg();
c1.setOprands(new int[]{10,20,30});
c1.sum();
c1.avg();
}
}
( 출처 생활코딩 https://www.opentutorials.org/course/1194/6088 )