※ 출처
https://fastcampus.co.kr/dev_online_javaend
https://zeddios.tistory.com/233
https://junghyun100.github.io/%ED%9E%99-%EC%8A%A4%ED%83%9D%EC%B0%A8%EC%9D%B4%EC%A0%90/
함수란(function)
- 여러 문장들이 하나의 기능을 구현하도록 구성한 것
- 구현된(정의된) 함수는 호출하여 사용하고 호출된 함수는 기능이 끝나면 제어가 변환됨
- 함수로 구현된 하나의 기능은 여러 곳에서 동일한 방식으로 호출되어 사용할 수 있음
- 독립된 기능을 수행하는 단위
함수 구현 예제
|
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
|
public class FunctionTest {
public static int addNum(int num1, int num2) {
int result = num1 + num2;
return result;
}
public static void sayHello(String greeting) {
System.out.println(greeting);
}
public static int calcSum() {
int sum = 0;
int i;
for (i = 0; i <= 100; i++) {
sum += i;
}
return sum;
}
public static void main(String[] args) {
int n1 = 10;
int n2 = 20;
int total = addNum(n1, n2);
System.out.println(total);
sayHello("안녕하세요");
total = calcSum();
System.out.println(total);
}
}
|
cs |
함수 호출과 스택 메모리
스택
- 함수의 호출과 관계되는 지역 변수와 매개변수가 저장되는 영역
- 함수의 호출과 함께 할당되며, 함수의 호출이 완료되면 소멸
- 스택 영역에 저장되는 함수의 호출 정보를 스택 프레임이라고 함
- 후입 선출(LIFO, Last-In First-Out) 방식에 따라 동작
- 메모리의 높은 주소에서 낮은 주소의 방향으로 할당
메서드(method)
- 객체의 기능을 구현하기 위해 클래스 내부에 구현되는 함수
- 멤버 함수 (member function)이기도 함
- 메서드를 구현함으로써 객체의 기능이 구현됨
- 메서드의 이용은 그 객체를 사용하는 객체(클라이언트)에 맞게 짖는 것이 좋음
ex) getStudentName() - 클래스, 구조체, 열거형에 포함되어있는 함수, 클래스 함수라고도 함
- 해당 클래스에 대한 객체가 생성되어야 사용할 수 있다
메서드 구현 예제
|
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
|
public class Student {
public int studentId;
public String studentName;
public String address;
public void showStudentInfo() {
System.out.println(studentId + "학번 학생의 이름은 " + studentName + "이고, 주소는 " + address);
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String name) {
studentName = name;
}
}
----------------------------------------------------------------
public class StudentTest {
public static void main(String[] args) {
Student studentLee = new Student(); // 인스턴스
studentLee.studentId = 12345;
studentLee.setStudentName("lee");
studentLee.address = "서울 강남구";
studentLee.showStudentInfo();
Student studentKim = new Student();
studentKim.studentId = 54321;
studentKim.studentName = "Kim";
studentKim.address = "경기도 성남시";
studentKim.showStudentInfo();
}
}
|
cs |
'Java > 객체지향 프로그래밍' 카테고리의 다른 글
| JAVA / 캡슐화(encapsulation) (0) | 2022.06.15 |
|---|---|
| JAVA / 접근 제어 지시자(access modifier)와 정보은닉(infomation hiding) (0) | 2022.06.13 |
| JAVA / 기본 자료형과 참조 자료형 (0) | 2022.06.10 |
| JAVA / 생성자 (0) | 2022.06.07 |
| JAVA / 객체와 객체 지향 프로그래밍 (0) | 2022.06.02 |