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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package quiz;
//<<<<<<<<<<<<overload method(중복함수)>>>>>>>>>>>>>>
public class Ex01_Method_OverloadMethod {
    
    //loopLine() {"--------------------"} 7회 "---" 출력하는 함수 
    public static void loopLine() {
        for(int i=0; i<7; i++) {
            System.out.print("---\t");
        }
    }
    
    //loopLine(int n) {"-------------------"} n회 "---"출력하는 함수 
    public static void loopLine(int n) {
        for(int i=0; i<n; i++) {
            System.out.print("---\t");
        }
    }
    
    //loopLint(int n1, int n2) {"---------------------"} n1~n2까지 "###"출력하는 함수
    public static void loopLine(int n1, int n2) {
//        for(int i=n1; i<n2; i++) {
//            System.out.print("###\t");
        if(n1 <= 0 || n2 <=0)
            return;
        
        if(n1>n2) {
            for(int i=n2; i<=n1; i++)
                System.out.print("### \t");
        } else {
            for(int i=n1; i<=n2; i++)
                 System.out.print("### \t");
        }
    }
    
    public static void main(String[] args) {
        System.out.println("loopLine()");
        loopLine();
        
        System.out.println("loopLine(2)");
        loopLine(2);
        
        System.out.println("loopLine(5,20)");
        loopLine(520);
        
        System.out.println("loopLine(0,0)");
        loopLine(0,0);
        
        System.out.println("end main");
    }
}
 
cs

-이름이 동일한 함수가 여러개 있는 경우 

-함수명 같고 매개변수의 개수가 다르거나, 

 매개변수의 개수가 같다면 자료형이 다른 함수 

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package ex04.argumentVariable;
 
//<<<<<<<<<<<<<가변길이인자: 동일한 데이터,길이가 가변적>>>>>>>>>>>>>>>>
public class Ex01_MainEntry {
    //가변 길이 인자(int...x) 와 overload(이름이 동일한 함수가 여러개 있는것) 사용
    
    //=========가변 길이 인자 이용(...) - 타입은 동일 + 길이가변적=========
    public static void plus(int...x) { 
        int sum=0;
        for(int i=0; i<x.length; i++) {
            sum += x[i];
//            System.out.print(x[i] + "\t");
        }        
        System.out.println("\n sum = " + sum);
    }
    
    //=========가변 길이 인자 이용(...) - 타입은 동일 + 길이가변적=========
    public static void plus(String...x) { //동일한 자료형이여야 한다 
        String sum = "";
        for(int i=0; i<x.length; i++) {
            sum +=x[i] + "";
        }
        System.out.println("String sum = " + sum);
    }
    
    //메인 
    public static void main(String[] args) {
        plus(99999);
        plus(123);
        plus(1020);
        plus(123456);
        plus("ab""k""ppp""dart""PDF");
        plus("ab","PDF");
 
    }
 
    //===========함수를 하나씩 다 만든 것===========>비효율적 
    /* 
    private static void plus(String string, String string2) {
        // TODO Auto-generated method stub
        
    }
 
    private static void plus(String string, String string2, String string3, String string4, String string5) {
        // TODO Auto-generated method stub
        
    }
 
    private static void plust(int i, int j, int k, int l, int m, int n) {
        int hap = i + j + k + l + m + n;
        System.out.println(hap);
        System.out.println(i + j + k + l + m + n);
    }
 
    private static void plust(int i, int j) {
        // TODO Auto-generated method stub
 
    }
 
    private static void plus(int i, int j, int k) {
        // TODO Auto-generated method stub
 
    }
 
    private static void plus() {
        System.out.println(1 + 100);
    }
     */
}
 
cs


 sum = 99999

 sum = 6

 sum = 30

 sum = 21
String sum = abkpppdartPDF
String sum = abPDF


▶가변 길이 인자 argument variable

   예) public static void plus(int...x) { 

        public static void plus(String...x) {

   1)동일한 데이터 타입으로만 이루어져야 한다.

   2)길이가 가변적 

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package ex01.method;
 
//static mehod: 객체 생성 없이 바로 사용 가능함
//호출형식> object.methodName();
//          ClassName.methodName();
 
class A {
    int x,y; //멤버변수 (A클래스 멤버변수 x,y)
    
    public static void setData(int xx, int yy) { //멤버함수 
        System.out.println(xx + "," + yy);
    }
}// A class end
 
 
 
public class Ex04_StaticMehtod { //public이 있어야 main메소드를 만들 수 있다 
    //파일의 이름과 일치하는 class가 public접근지정자여야 함 
    
    public static void disp() {
        System.out.println("thh787878787878");
    }
    
    //main
    public static void main(String[] args) { //static 메소드
        //static메소드 호출 방법1-1 ClassName.methodName(); - 같은 클래스에 있는 static 메소드 호출하기 
        Ex04_StaticMehtod.disp(); //ClassName.methodName();
        
        //static메소드 호출 방법1-2 ClassName.methodName(); - 다른 클래스에 있는 static 메소드 호출하기 
        A.setData(12);
        
        //static메소드 호출 방법2 - object.methodName()
        A obj = new A(); //객체생성, 메로리에 할당, 생성자함수 자동호출 
        obj.setData(34); //object.methodName()
        
        obj.x = 99;
        obj.y = 20;
        System.out.println(obj.x + ":" + obj.y);
    }
 
}
 
 
class C{
    
}
 
//하나의 페이지에 여러개의 클래스가 존재하면, 
//반드시 public 접근지정자 클래스는 1개만 <------여기에 main method 들어가야 함 
cs

thh787878787878
1,2
3,4
99:20


 

▶static method 호출형식 2가지

  1. object.methodName();
  2. ClassName.methodName();

<instance method>

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
35
36
37
38
39
package ex01.method;
 
//instance method
//->객체 생성하고 사용해야함(메모리상에 할당이 되어야 사용가능)
 
class B{
    int x,y;
    
    public void setData(int xx, int yy) {
        System.out.println(xx + "," + yy);
    }
    
}//B class end 
 
 
public class Ex03_InstanceMethod {
    //메인
    public static void main(String[] args) {
        //객체(=다른 클래스에 들어갈 수 있는 key!) 생성, 메모리에할당됨, 생성자함수 자동호출
        B b = new B();
        b.setData(993);
 
        //객체는 여러개 생성가능(객체이름은 중복x)
        B bb = new B();
        bb.setData(1020);
        
        //1.instance method 호출 방법-같은 class에 있어도 객체를 생성해서 호출해야함
        //disp(); -> 그냥 부르면 안됨
        Ex03_InstanceMethod im = new Ex03_InstanceMethod();
        im.disp();
    }
    
    //===========1.instance 메소드============
    public void disp() { //static이 없다..->main에서 객체 생성후 불러줘야 함 
        System.out.println("같은 class안에 있는 메소드");
    }
 
}//Ex03_InstanceMethod class end 
 
cs

99,3
같은 class안에 있는 메소드
10,20


-객체 생성하고 사용해야함 (메모리상에 할당이 되어야 사용가능)

-instance method 호출 방법: 같은 class에 있어도 객체를 생성해서 호출해야함


<static method>

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
35
36
37
package ex01.method;
 
//instance method
//->객체 생성하고 사용해야함(메모리상에 할당이 되어야 사용가능)
 
class B{
    int x,y;
    
    public void setData(int xx, int yy) {
        System.out.println(xx + "," + yy);
    }
    
    //================2.static method 객체 생성 없이 호출 가능================= 
    public static void show(String name) {
        System.out.println(name);
    }
}//B class end 
 
 
public class Ex03_InstanceMethod {
    public static void main(String[] args) {
        //객체(=다른 클래스에 들어갈 수 있는 key!) 생성, 메모리에할당됨, 생성자함수 자동호출
        B b = new B();
        b.setData(993);
        
        //2.static method 호출 방법1 - 객체 생성 x (이걸로 쓰기)
        B.show("syr111111");
        //2.static method 호출 방법2 - 객체 생성 o (참고만)
        b.show("syr222222"); 
        
        //객체는 여러개 생성가능(객체이름은 중복x)
        B bb = new B();
        bb.setData(1020);
    }
    
}
 
cs

 

99,3
syr111111
syr222222
10,20


-객체 생성하고 사용해야함(메모리에 할당이 되어야 사용가능

▶static method 호출 방법 2가지

   1)객체 생성 안하는 경우 -> 이걸로 쓰기!

   2)객체 생성 하는 경우 

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package ex01.method;
 
public class Ex02_Method {
 
    //==========char타입===========
    public static char disp(int jumsu) { //함수정의부(구현부)
        char grade = ' ';
        
        switch (jumsu / 10){
            case 10
            case 9: grade='A'break;
            case 8: grade='B'break;
            case 7: grade='C'break;
            case 6: grade='D'break;
            
            default: grade = 'F'break;
        } // end switch
        return grade;
    } //disp() end
    
    //<<<<<<<<<<<<<<메인>>>>>>>>>>>>>>>
    public static void main(String[] args) {
        System.out.println("grade = " + disp(99+ "학점");
        
        char ch = disp(55); //함수호출
        System.out.println("grade = " + ch + "학점");
        
        System.out.println("-----------------------------");
        
        //==========main에서 설계함수를 미리 쓴 후->관련 함수 작성(자동완성가능)=========
        sub(10,20);
    }
 
    public static void sub(int x, int y) {
        //항상 양수 결과값만 출력하기 
        //방법1-if else
        if(x>y) System.out.println(x + "-" + y + "=" + (x-y));
        else System.out.println(y + "-" + x + "=" + (y-x));
        
        //방법2-삼항연산자
        int result = 0;
        result = (x<y) ? (y-x):(x-y);
        System.out.println("result = " + result);
        
        //cf)함수에서 다른함수 호출도 가능 
        System.out.println("sub에서 호출했어요 ==> " + disp(77+ "학점");
    }
    
}
 
cs

grade = A학점
grade = F학점
-----------------------------
20-10=10
result = 10
sub에서 호출했어요 ==> C학점


▶main에서 설계함수를 미리 쓴 후->관련 함수 작성(자동완성가능)

 

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
package ex01.method;
 
public class Ex01_MaintEntry {
 
    // 메인
    public static void main(String[] args) {
        
 
    }
 
    
    //===========return자료형과 매개변수 자료형의 크기에 따른 차이 비교============
        //1.return 타입의 크기가 더 클 경우 -> 자동 형변환 가능 
        public static double sub(int x) {
            return x; //이 경우에는 자동 형변환이 됨->오류 안남!!
        }
 
        //2.매개변수의 타입이 리턴타입보다 더 클경우 -> 에러
        public static int sub(double x) {
            return x; 
            // return x;는 오류->리턴타입(double)과 같아야함
        }
        
}
 
cs

1.return 자료형의 타입 > 매개변수의 타입

  : 자동 형변환 가능

 

2.return 자료형의 타입 < 매개변수의 타입

  : 자동 형변환 불가능 

'JAVA > 10_method' 카테고리의 다른 글

argument variable - 가변길이 인자  (0) 2021.01.18
static method - 객체 생성 없이 바로 사용 가능  (0) 2021.01.18
instance method와 static method  (0) 2021.01.18
char타입 리턴  (0) 2021.01.18
return; 제어권 넘김  (0) 2021.01.18
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package ex01.method;
 
public class Ex01_MaintEntry {
 
    // 메인
    public static void main(String[] args) {
        show("hi~!"); // 함수호출
 
        String[] arr = { "kbs""sbs""korea""seoul" };
        view(arr);
        // 시스템크기는 int타입의 크기를 갖는다->배열arr자체는4byte
        // arr은 실제데이터(배열값들)가 있는곳의 주소를 참조하는 참조변수
 
        plus();
 
    }
 
    public static void show(String str) { // 함수 정의부(구현부)
        System.out.println(str);
    }
 
    public static void view(String[] str) { // 함수 정의부(구현부)
        System.out.println(str); // str자체는 실제데이터가 있는 주소가 들어감,
        System.out.println();
        System.out.println(str[0]); // 배열안의 내용을 출력하려면 구체적이 배열형식으로 써야함
 
        for (int i = 0; i < str.length; i++) {
            System.out.println(str[i]);
        }
    }
 
    //===========return; 제어권 넘김==============
    public static void plus() {
        int x = 3;
        System.out.println("21.01.18");
        System.out.println("21.01.19");
        System.out.println("21.01.20");
 
        for (int i = 0; i < 5; i++) {
            if (x < 0) {
                return// ==>이부분에서 제어권을 넘김, return아래의 부분은 실행 x
            }
            x--;
        }
        System.out.println("return; ==> 제어권 넘김 ");
    }
 
 
}
cs

hi~!

Ljava.lang.String;@15db9742


kbs
kbs
sbs
korea
seoul
21.01.18
21.01.19
21.01.20


return; => 제어권을 넘김,

+ Recent posts