Method
Method란?
어떠한 특정 작업을 수행하기 위한 명령문의 집합
Method를 사용하는 이유
- 모듈성: 코드의 복잡성을 줄이고 이해하기 쉬워짐
- 유지보수: 프로그램 수정이나 확장이 용이해져 유지보수가 쉬워짐
- 재사용성: 중복되는 코드의 반복적인 프로그래밍 회피
Method의 기본 구조
접근제한자 반환타입 메서드명(매개변수목록) { //선언부
// 메서드 몸체
// 수행할 코드
return 반환값; // 반환타입이 void가 아닐 경우 필요
}
접근제어자 :
해당 메소드에 접근할 수 있는 범위를 명시
- public: 외부 클래스에서 자유롭게 사용할 수 있다.
- protected: 같은 패키지 또는 자식 클래스에서 사용할 수 있다.
- private: 외부에서 사용할 수 없다. (클래스 내부에서만 사용가능)
- default: 같은 패키지에 소속된 클래스에서만 사용할 수 있다.
반환 타입 :
메서드가 작업을 수행한 후 반환하는 데이터의 타입(int,float,string 등)
반환 값이 없을 때는 void로 지정합니다.
메서드명 : 이름
매개변수목록 : 메소드 호출 시에 전달되는 인수의 값
메서드 몸체 : 수행할 코드
//메서드 예시
class Calculator {
public int add(int num1, int num2) {
int sum = num1 + num2;
return sum;
}
}
public class Test {
public static void main(String[] args) {
int a = 3;
int b = 7;
Calculator cal = new Calculator();
int result = cal.add(a, b);
System.out.println(result);
}
}
결과값 : 10
Static
static을 붙인 변수와 메서드는 인스턴스에 속하지 않고 클래스에 고정됨
//static 예시
class Number {
static int sNum = 0;
int Num = 0;
}
public class Test {
public static void main(String[] args) {
Number testNum1 = new Number();
Number testNum2 = new Number();
testNum1.sNum++;
testNum1.Num++;
System.out.println(testNum2.sNum);
System.out.println(testNum2.Num);
}
}
결과값 : 1
결과값 : 0
this() method
생성자 내부에서만 사용할 수 있으며, 같은 클래스의 다른 생성자를 호출할 때 사용
class Car {
private String modelName;
private int modelYear;
private String color;
private int maxSpeed;
private int currentSpeed;
Car(String modelName, int modelYear, String color, int maxSpeed) {
this.modelName = modelName;
this.modelYear = modelYear;
this.color = color;
this.maxSpeed = maxSpeed;
this.currentSpeed = 0;
}
Car(String modelName, int modelYear) {
this.modelName = modelName;
this.modelYear = modelYear;
this.color = "red";
this.maxSpeed = 50;
this.currentSpeed = 0;
}
Car() {
this("sonata", 2012, "black", 160);
}
public String getModel() {
return modelYear + "year " + modelName + " " + color;
}
}
public class Method05 {
public static void main(String[] args) {
Car tcpCar = new Car("genesis", 2013);
System.out.println(tcpCar.getModel());
}
}
결과값 : 2013year genesis red
void() method
public class Method {
public static void main(String[] args) {
NamePrint("홍길동"); // NamePrint 메서드 호출
NamePrint("김철수"); // NamePrint 메서드 호출
NamePrint("박영희"); // NamePrint 메서드 호출
NamePrint("강아지"); // NamePrint 메서드 호출
NamePrint("고양이"); // NamePrint 메서드 호출
}
// NamePrint 메서드 선언
public static void NamePrint(String Name) {
System.out.println(Name);
}
}
결과값: 홍길동
김철수
박영희
강아지
고양이
'Android Development > Java' 카테고리의 다른 글
java의 작동 원리 (1) | 2024.09.13 |
---|---|
Java 필드(Field)의 개념과 사용 방법 (1) | 2024.09.11 |
Java Class & constructor 개념 정리 (2) | 2024.09.09 |