37-java - 메소드 기본 이론

jin·2022년 7월 30일
0

이하 수업 내용

1. 메소드의 기본 구조

매서드 기본구조
정의
1) void ==> 키워드
2) testPrint() ==> 이름
3) {기능} ==> 실행되는 영역

2. 메소드의 사용방법

2-1 사용법1

t1.testPrint();
1) t1 ==> 클래스변수명
2) .testPrint(); ==> .함수이름();

class Test{		
	void testPrint() {
		System.out.println("!!");
	}
}

public class 메서드1_기본이론1 {
	public static void main(String[] args) {
		Test test = new Test();
		test.testPrint();
		test.testPrint();
		test.testPrint();
		test.testPrint();
	}
}

2-2 사용법 2

test1.setNums(10, 20);
1) test1 ==> 클래스변수명
2) .setNums ==> .함수이름
3) (10, 20); ==> (전달할값); (전달인자 / 어그먼트)

class Test3 {
	int num1;
	int num2;
	
	void setNums(int a, int b) {
		num1 = a;
		num2 = b;
	}
	
	void printNums() {
		System.out.println(num1 + " " + num2);
	}
}

public class 메서드1_기본이론3 {
	public static void main(String[] args) {
		// 아래와같이 같을 저장해서 출력 할수도있지만,
		// 매서드를 만들어서 사용할수도있다.
		Test3 t3_1 = new Test3();
		t3_1.num1 = 10;
		t3_1.num2 = 20;
		System.out.println(t3_1.num1 + " " + t3_1.num2);
		
		Test3 t3_2 = new Test3();
		t3_2.setNums(10, 20);
		t3_2.printNums();
		
	}
}

2-3 사용방법3 (리턴)

리턴의 사용방법 (2)
return 매서드를 사용하면 클래스내의 변수한개를 줄일수있다.
굳이 쓰지않아도 프로그램 만드는데는 아무런지장이 없다.
하지만 프로그래밍이 능숙해지면 자연히쓰게된다.

리턴메서드 만드는법
1) int ==> main 으로 보낼 자료형
2) plus(int a , int b) ==> 이름
3) { return + 내보낼 값 } ==> 이값은 main 으로 보내진다.

class TestReturn2_1{
	int result;
	void plus(int a , int b) {
		result = a + b;
	}	
}

class TestReturn2_2{
	int plus(int a , int b) {
		// result 변수가 없어도 기능을 만들수있다. 
		return a + b;
	}
}
public class H3_메서드리턴1_기본이론2 {
	public static void main(String[] args) {
		TestReturn2_1 t1 = new TestReturn2_1();
		t1.plus(10, 3);
		int num1 = t1.result;
		System.out.println(num1);
		
		System.out.println("---------------------------");
		TestReturn2_2 t2 = new TestReturn2_2();
		int num2 = t2.plus(10, 3);
		System.out.println(num2);
				
	}
}

2. 오버로딩

// 매서드오버로딩이란? 메서드를 같은이름으로 만들어도 전달되는 값이 다르면 서로 다른 매서드로 인식하겠다. 
class MethodOverloading{
	int add(int x, int y) {
		return x + y;
	}
	int add(int x, int y, int z) {
		return x + y + z;
	}
	int add(int[] arr) {
		int total = 0;
		for (int i = 0; i < arr.length; i++) { total += arr[i]; }
		
		return total;
	}
}
public class H3_메서드리턴1_기본이론5_오버로딩 {
	public static void main(String[] args) {
		MethodOverloading mol = new MethodOverloading();
		
		int[] arr = { 1, 2, 3, 4, 5 };

		int r1 = mol.add(10, 3);
		int r2 = mol.add(10, 3, 1);
		int r3 = mol.add(arr);
		
		System.out.println("r1 = " + r1);
		System.out.println("r2 = " + r2);
		System.out.println("r3 = " + r3);
	}
}

0개의 댓글