오버 로딩
정수형 + 정수형
정수형 + 실수형을 모두 수행하는 class Calc를 만들어보자
class Calc{ //모든 class에 extends Object가 생략되어 있다.
int x,y=0;
public void add(int x, int y) {
this.x = x;
this.y = y;
int result = x+y;
System.out.println(result);
}
public void add(int x, double y) { //함수 오버로딩
double result = x+y;
System.out.println(result);
}
public String toString() {
return getClass().getName() + "(" + x + "," + y + ")";
}
}
public class MethodEx {
public static void main(String[] args) {
Calc c = new Calc();
c.add(5, 5);
c.add(5, 0.5);
System.out.println(c);
}
}
실행결과
10
5.5
Calc(5,5)
오버 라이딩
class Point{
int x,y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() { //Object 클래스의 toString() 오버라이딩
String a = getClass().getName() + "(" + x + "," + y + ")";
return a;
}
}
public class ToStringEx {
public static void main(String[] args) {
Point p = new Point(2,3);
System.out.println(p); // -> System.out.println(p.toString());
}
}
실행결과
Point(2,3)
'Java' 카테고리의 다른 글
[Java] 상속 - 메시지 전송 프로그램 (0) | 2022.12.04 |
---|---|
[Java] 상속 - 계좌 프로그램 (0) | 2022.12.02 |
[Java] try catch 예외 처리 (0) | 2022.10.22 |
[Java] main() 메소드의 매개변수 args[] (0) | 2022.10.22 |
[Java] Class (0) | 2022.10.22 |