메소드, 오버로드

Moon·2024년 2월 22일

Java

목록 보기
11/45

메소드의 선언과 정의

class Person {
    String name;
    
    Person(String name) { 
        this.name = name;
    }
    
    
    void setName(String name) { //반환값 x, 매개변수 o
        this.name = name;
    }
    
    String getName() { //반환값 o, 매개변수 x
        return name;
    }
}

반환값 없는 메소드도 return 키워드 존재 가능.

메소드 실행 도중 종료되길 원할 때.

class Study {
    boolean isStuding;

    void start() {
        if (isStudying) {
            System.out.println("이미 공부중이다");
            return;
        }
        isStudying = true;
        System.out.println("공부를 시작한다");
    }
}

정적 메소드

정적메소드는 인스턴스 변수 쓸 수 없다. (수명주기가 다름)
정적메소드는 정적 변수만 쓸 수 있다.

class Utils {
    // 인스턴스 변수
    int c = 3;
 
    static int plus(int a, int b) {
        // 인스턴스 변수 c에 접근할 수 없다 
        return a + b + c;
    }
}
error: non-static variable name cannot be referenced from a static context
class Utils {
    // 정적 변수
    static int c = 3;
 
    static int plus(int a, int b) {
        return a + b + c;
    }
}

메소드 오버로딩

0개의 댓글