관리 메뉴

커리까지

함수와 메서드 본문

자바

함수와 메서드

목표는 커리 2021. 6. 28. 04:41
728x90
SMALL

함수

  • 하나의 기능을 수행하는 코드셋
  • 호출되면 수행됨
  • 구현된 기능은 여러곳에서 사용가능
  • 그래서 유용함

함수 정의

  • 함수는 이름, 매개 변수, 반환 값, 함수 몸체고 구성
  • 반환 값이 있을 때
public static int plus(int num1, int num2) {
        int result;
        result = num1 + num2;
        return result;
    }
  • 반환 값이 없을 때
    • void를 입력
public static void sayHello(String greeting) {
        System.out.println(greeting);
    }

함수 호출과 스택 메모리

  • 스택 : 함수가 호출 될 때 지역 변수들이 사용하는 메모리
public static int plus(int num1, int num2) {
        int result;
        result = num1 + num2;
        return result;
}
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);
    }

}
  • plus나 num1, num2는 매개변수
    • 또한 지역변수
  • main에도 n1, n2와 같은 지역변수 존재
  • 처음에 main에 있는 지역 변수들의 변수가 메모리 공간이 스택에 형성됨
  • 그 다음에 add가 호출되면 add 함수가 메모리 공간이 스택에 형성되고 끝나면 사라짐

메서드

  • 객체 기능을 구현하기 위해 클래스 내부에서 구현되는 함수를 말함
  • 위에서 멤버 함수
  • 이름은 객체를 사용하는 객체랑 알맞게 하는게 좋음
public class Student {


        public int studentID;
        public String studentName;

        public void showStudentInfo() {
            System.out.println(studentID + studentName);
    }


     public String getStrdentName() {
         return studentName;
     }

     public void setStudentName(String name) {
         studentName = name;
     }
}
  • 필요한 변수들을 선언
  • 학생의 이름을 얻기위한 함수 구현
  • 학생의 이름을 설정하기 위한 함수 구현
public class StudentTest {

    public static void main(String[] args) {


        Student studentOne = new Student();


    }

}
  • 학생 클래스를 사용하기 위한 클래스
  • studentOne는 Student의 인스턴스
public class StudentTest {

    public static void main(String[] args) {


        Student studentOne = new Student();

        studentOne.studentID = 1234;
        studentOne.setStudentName("One");
        studentOne.address = "서울";

    }

}
  • 이런식으로 인스턴스를 만들어서 속성을 정의
728x90
LIST

'자바' 카테고리의 다른 글

생성자  (0) 2021.07.02
인스턴스 생성과 힙 메모리  (0) 2021.06.30
객체 지향 입문  (0) 2021.06.27
break 문  (0) 2021.06.25
중첩 반복문  (0) 2021.06.23
Comments