[java] 함수와 메서드

DEVELOPERS_Ivan ㅣ 2023. 7. 28. 01:35

함수와 메서드
함수(function) ​
● 하나의 기능을 수행하는 일련의 코드
● 구현된(정의된) 함수는 호출하여 사용하고 호출된 함수는 기능이 끝나면 제어가 반환됨
● 함수로 구현된 하나의 기능은 여러 곳에서 동일한 방식으로 호출되어 사용될 수 있음
● TIP. 함수 정의하기 : 함수는 이름, 매개 변수, 반환 값, 함수 몸체(body)로 구성됨
● TIP. 함수 호출과 스택 메모리 스택 메모리: 함수가 호출될 때 지역 변수들이 사용하는 메모리 함수의 수행이 끝나면 자동으로 반환 되는 메모리

메서드 (method)​
● 객체의 기능을 구현하기 위해 클래스 내부에 구현되는 함수
● 멤버 함수 (member function)이라고도 함
● 메서드를 구현함으로써 객체의 기능이 구현 됨

● TIP. 함수와 메서드의 차이점 메서드는 멤버 변수를 활용해서 그 객체에 이름에 맞는 기능을 정의하는 것이다, 함수는 하나의 기능을 수행하는 일련에 코드의 묶음이다.

함수(호출) 정의 / 스택(메모리) 정의

 

// 함수와 메서드_함수 호출하기#1

 

package ch02;

 

public class FunctionMainTest1 {

 

// 함수란?

 

// 두 개에 매개 변수를 받아서 덧셈하는 기능을 만들기

 

// 함수를 선언하는 문법

// (int n1, int n2) 를 "매개변수" 라고 부른다.

public static int addNumber(int n1, int n2) {

 

// 결과를 담을 변수를 선언

int result;

result = n1 + n2;

return result;

 

} // end of addNumber

 

public static double minusNumber(int n1, int n2) {

double result;

result = n1 - n2;

return result;

 

}

 

public static void main(String[] args) {

 

// 함수를 호출하는 문법

// 함수 호출은 모양 맞추기다

int returnValue = addNumber(10, 5);

System.out.println(returnValue);

int returnValue2 = addNumber(100, 7898);

System.out.println(returnValue2);

double returnValue3 = minusNumber(5, 100);

System.out.println(returnValue3);

 

} // end of main

 

} // end of class

Console 보기

15

7998

-95.0

 

// 함수와 메서드_함수 호출하기#2

package ch02;

 

public class FunctionMainTest2 {

// 메인 함수

public static void main(String[] args) {

sayHello("안녕 좋은 아침이야");

sayHello("반가워~");

int result = calcSum();

System.out.println(result);

 

} // end of main

 

// 함수에는 여러 개 종류가 있다. - 정수 값을 반환하는 함수

public static int add(int n1, int n2, int n3) {

// 함수 안에 사용하는 변수는 지역 변수라고 한다.

// return 키워드 뒤에 바로 식을 사용할 수도 있다.

return n1 - n2 - n3;

} // end of add

 

// 아무것도 반환하지 않는 함수도 있다.

 

public static void sayHello(String greeting) {

 

System.out.println(" ** " + greeting + " ** ^^");

 

} // end of sayHello

 

// 매개 변수는 반드시 없어도 된다.

public static int calcSum() {

 

int sum = 0;

int i = 1;

for (i = 1; i <= 100; i++) {

sum += i;

 

} // end of for

 

return sum;

 

} // end of calcSum

 

} // end of class

Console 보기

** 안녕 좋은 아침이야 ** ^^

** 반가워~ ** ^^

5050

 

// 함수와 메서드_함수 호출하기#3

package ch02;

 

import ch01.User;

 

public class FunctionMainTest3 {

 

// 메인 함수(코드에 시작점)

public static void main(String[] args) {

// total <--- 기본 데이터 타입, (지역 변수)

int total = (int) minus(10.0, 5.0);

System.out.println(total);

 

// kim <--- 참조 타입, (지역변수)

User kim = new User();

System.out.println(kim);

 

} // end of main

 

// 함수를 만들어 주세요.

// 리턴 값이 실수형인 minus 라는 이름을 가진 함수를 선언

// 매개변수는 실수형 2개를 받는 녀석을 선언해 주세요.

// n1 에서 n2 뺴는 기능

public static double minus(double n1, double n2) {

// 지역 변수 : 스택 메모리에

double result = n1 - n2;

return result;

} // end of minus

 

} // end of class

Console 보기

5

ch01.User@7c30a502

 

// 함수와 메서드_함수 호출하기#4

package ch02;

 

import ch01.User;

 

public class FunctionMainTest4 {

 

// 메인 함수(코드에 시작점)

public static void main(String[] args) {

// 이 범위는 지역 변수

System.out.println("======== 문제 ========");

// 함수를 호출해서 실행하시오. (+,-,*, / )

 

// 함수 이름(매개변수...);

int plustotal = plus(30, 20, 10);

int minutotal = minus(30, 20, 10);

int multiplicationtotal = multiply(30, 20, 10);

int dividetota = divide(30, 20, 10);

 

System.out.println(plustotal);

System.out.println(minutotal);

System.out.println(multiplicationtotal);

System.out.println(dividetota);

 

} // end of main

 

// 함수 3개를 선언하시오.

// 더하기

public static int plus(int n1, int n2, int n3) {

int result = n1 + n2 + n3;

return result;

} // end of plus

// 빼기

 

public static int minus(int n1, int n2, int n3) {

int result = n1 - n2 - n3;

return result;

} // end of minus

// 곱셉

 

public static int multiply(int n1, int n2, int n3) {

int result = n1 * n2 * n3;

return result;

} // end of plus

//나눗셈

 

public static int divide(int n1, int n2, int n3) {

int result = n1 / n2 / n3;

return result;

} // end of divide

} // end of class

Console 보기

======== 문제 ========

60

0

6000

0


// 함수와 메서드_메서드 예제1.Bus

 

package ch03;

 

public class Bus {

 

// 함수와 메서드의 차이점

// 메서드는 멤버 변수를 활용해서 그 객체에 이름에 맞는 기능을 정의하는 것이다.

// 함수는 하나의 기능을 수행하는 일련에 코드의 묶음이다.

 

// 멤버 변수 파란색 지역변수 노란색

 

// 속성

int busNumber;

int count;

int money; // 수익금

 

// 기능

public void take(int m) {

// 0 = 0 + 1300; .... 1300

// 1300 = 1300 + 1300; .... 2600

// money = money + m;

money += m;

count = count + 1;

 

} // end of take

 

public void showinfo() {

System.out.println("==== 상태 창 ==== ");

System.out.println("버스 번호 : " + busNumber);

System.out.println("승객 수 : " + count);

System.out.println("현재 수익금 : " + money);

} // end of showinfo

 

} // end of class

 

// 함수와 메서드_메서드 예제1.Bus

 

package ch03;

 

public class BusMainTest {

 

public static void main(String[] args) {

 

Bus bus100 = new Bus();

Bus bus200 = new Bus();

// System.out.println(bus100);

 

for (int i = 1; i < 1; i++) { // 1사람 탑승

bus100.take(1300);

} // end of for

 

for (int i = 1; i < 2; i++) { // 2사람 탑승

bus200.take(1300);

} // end of for

 

bus100.busNumber = 100;

bus100.take(1300);

 

bus200.busNumber = 200;

bus200.take(1300);

 

bus100.showinfo();

bus200.showinfo();

 

} // end of main

 

} // end of class

 

// 함수와 메서드_메서드 예제1.Bus

 

package ch03;

 

public class BusMainTest {

 

public static void main(String[] args) {

 

Bus bus100 = new Bus();

Bus bus200 = new Bus();

// System.out.println(bus100);

 

for (int i = 1; i < 1; i++) { // 1사람 탑승

bus100.take(1300);

} // end of for

 

for (int i = 1; i < 2; i++) { // 2사람 탑승

bus200.take(1300);

} // end of for

 

bus100.busNumber = 100;

bus100.take(1300);

 

bus200.busNumber = 200;

bus200.take(1300);

 

bus100.showinfo();

bus200.showinfo();

 

} // end of main

 

} // end of class

 

Console 보기

==== 상태 창 ====

버스 번호 : 100

승객 수 : 1

현재 수익금 : 1300

==== 상태 창 ====

버스 번호 : 200

승객 수 : 2

현재 수익금 : 2600

 

// 함수와 메서드_메서드 예제2.Student

package ch03;

 

public class Student {

// 멤버 변수

int studentld; // 기본 데이터 타입

String studentname; // 참조 타입

String address;

double weight;

 

// 기능 정의

public void study() {

System.out.println(studentname + " 이(가) 공부를 합니다.");

} // end of study

 

public void breakTime() {

System.out.println(studentname + " 이(가) 휴식을 합니다.");

} // end of breakTime

 

public void showInfo() {

System.out.println("==== 상태창 ====");

System.out.println(studentname + " 에 ID : " + studentld);

System.out.println(studentname + " 에 name : " + studentname);

System.out.println(studentname + " 에 주소 : " + address);

System.out.println(studentname + " 에 몸무게 : " + weight);

System.out.println("====================");

 

} // end of showInfo

 

} // end of class

 

// 함수와 메서드_메서드 예제2.Student

 

package ch03;

 

public class StudentMainTest1 {

public static void main(String[] args) {

 

Student studentKim = new Student();

studentKim.studentld = 1;

studentKim.studentname = "티모";

studentKim.address = "블루진영";

 

studentKim.study();

studentKim.breakTime();

studentKim.showInfo();

 

Student studentLee = new Student();

studentLee.studentld = 2;

studentLee.studentname = "야스오";

studentLee.address = "레드진영";

 

studentLee.study();

studentLee.breakTime();

studentLee.showInfo();

 

// 멤버 변수는 값을 초기화 하지 않으면 기본값으로

// 컴파일러가 값을 넣어서 만들어 준다.

 

} // end of main

 

} // end of class

Console 보기

티모 이(가) 공부를 합니다.

티모 이(가) 휴식을 합니다.

==== 상태창 ====

티모 에 ID : 1

티모 에 name : 티모

티모 에 주소 : 블루진영

티모 에 몸무게 : 0.0

====================

야스오 이(가) 공부를 합니다.

야스오 이(가) 휴식을 합니다.

==== 상태창 ====

야스오 에 ID : 2

야스오 에 name : 야스오

야스오 에 주소 : 레드진영

야스오 에 몸무게 : 0.0

====================