'2008/08/06'에 해당되는 글 1건
- 2008.08.06 Part 2 & 3 메소드와 클래스
Part 2 & 3 메소드와 클래스
1. 메소드 오버로딩이란?
한 메소드에 대해 여러번 정의할 수 있는데 이름이 같아도 메소드의 자료형과 전달인자의 개수로 구분이 가능하다.
package training;
class YourMath {
static double max=0;
public static int max(int a,int b) {
if(a>b)
max=a;
else
max=b;
return (int)max;
}
public static long max(long a,long b) {
if(a>b)
max=a;
else
max=b;
return (long)max;
}
public static float max(float a,float b) {
if(a>b)
max=a;
else
max=b;
return (float) max;
}
public static double max(double a,double b) {
if(a>b)
max=a;
else
max=b;
return max;
}
}
public class Ex02 {
public static void main(String[] args) {
System.out.println(YourMath.max(10, 20));
System.out.println(YourMath.max(4L, 2L));
System.out.println(YourMath.max(4.2f, 2.3f));
System.out.println(YourMath.max(4.24, 2.35f));
}
}
2. Varargs
메소드 내의 기능이 같더라도 전달인자의 개수에 따라 다양하게 호출하기 위해서는 메소드를 여러번 정의해야 하지만 아래처럼 Varargs를 쓰면 한방에 끝난다.
// Varargs를 이용한 출력
package training;
public class Ex04 {
public static void prn(int ... a){
for(int i=0;i<a.length;i++)
System.out.print(a[i] + " ");
System.out.println();
}
public static void main(String[] args) {
prn(10);
prn(10,20);
prn(10,20,30);
}
}
3. 레퍼런스와 지역변수의 변화를 확인하는 소스
package pack03;
class MyDate {
int year; int month; int day; // int 형은 초기값이 0 이다.
}
public class Ex01 {
static void changeInt(int y){
y+=5;
}
static void changeRef(MyDate ref){
ref.day+=5;
}
static MyDate createObject(MyDate ref) {
ref=new MyDate();
return ref;
}
public static void main(String[] args) {
int x=10;
MyDate d=new MyDate();
for(int i=0;i<5;i++){
changeInt(x); // main 지역 변수 x를 changInt 메소드에 입력 시켜서 y 값이 증가하지만
// 출력 되는 값은 지역변수 설정값에 적용 시키지 못한다.
changeRef(d); // MyDate형의 ref 변수에 레퍼런스 d의 초기값 0/0/0을 대입하고
// day에 5를 더하여 그 값을 간직하고 있다. <- 이 말이 맞는 말인가???
System.out.println(x);
System.out.println(d.year + " : " + d.month + " : " + d.day );
}
System.out.println("=====================================");
MyDate t; // 새로운 레퍼런스 t를 만든다
t=createObject(d); // createObject메소드에 d의 값을 입력하여 t 값을 생성하지만
// t는 기존의 실매개변수 0/0/0 을 받아서 ref에 저장하고 t로 리턴한다.
System.out.println("1 " + d.year + " : " + d.month + " : " + d.day );
System.out.println("2 " + t.year + " : " + t.month + " : " + t.day );
d.year=2007; d.month=7; d.day=19;
System.out.println("3 " + d.year + " : " + d.month + " : " + d.day );
System.out.println("4 " + t.year + " : " + t.month + " : " + t.day );
t.year=2008; t.month=8; t.day=6;
System.out.println("5 " + d.year + " : " + d.month + " : " + d.day );
System.out.println("6 " + t.year + " : " + t.month + " : " + t.day );
t=createObject(d);
System.out.println("7 " + d.year + " : " + d.month + " : " + d.day );
System.out.println("8 " + t.year + " : " + t.month + " : " + t.day );
}
}
'수업 > 자바2JDK입문' 카테고리의 다른 글
Part 4. 상속 I (0) | 2008.08.08 |
---|---|
Part 3. static (2) | 2008.08.07 |
Part 3. 생성자 (0) | 2008.08.07 |
Part2. 메소드 나머지 부분 & Part 3. 클래스와 객체(11. 클래스와 객체) (3) | 2008.08.05 |
PART 2(7 제어문의 다양한 활용 ~ 10 사용자정의 메서드 만들기) (0) | 2008.08.04 |