메소드 선언
- 객체의 동작을 실행 블록으로 정의하는 것.
출처, 이것이 자바다
- 리턴 타입: 메소드 실행 후 호출한 곳으로 전달하는 결과값의 타입
- 메소드명: 메소드명은 첫 문자를 소문자로 시작하고, 캐멀 스타일로 작성
- 매개변수: 메소드를 호출할 때 전달한 매개값을 받기 위해 사용
- 실행 블록: 메소드 호출 시 실행되는 부분
메소드 호출
- 메소드 블록을 실제로 실행하는 것
- 클래스로부터 객체가 생성된 후에 메소드는 생성자와 다른 메소드 내부에서 호출될 수 있고, 객체 외부에서도 호출될 수 있음
- 외부 객체에서는 참조 변수와 도트(.) 연산자로 호출
출처, 이것이 자바다
package ch06.sec08.exam01;
public class Calculator {
//필드선언
//메소드 선언
//1)리턴값이 없는 메소드 선언. void
void powerOn() {
System.out.println("전원을 킵니다.");
}
void powerOff() {
System.out.println("전원을 끕니다.");
}
//두 정수값을 전달받아서 더한 값을 호출한 쪽으로 보내는 메소드
int plus(int x, int y) {
int result = x + y;
return result;
}
//두 정수값울 전달받아서 나눈 결과값을 리턴하는 메소드 선언
double divide(int x, int y) {
double result = (double)x / y;
return result;
}
}
package ch06.sec08.exam01;
public class CalculatorExample {
public static void main(String[] args) {
Calculator myCalc = new Calculator();
myCalc.powerOn();
int result1 = myCalc.plus(5, 6);
System.out.println("result1: " + result1);
int x = 10;
int y = 4;
double result2 = myCalc.divide(x, y);
System.out.println("result2: " + result2);;
myCalc.powerOff();
}
}
가변길이 매개변수
- 메소드가 가변길이 매개변수를 가지고 있다면 매개변수의 개수와 상관없이 매개값을 줄 수 있음
출처, 이것이 자바다
- 메소드 호출 시 매개값을 쉼표로 구분해서 개수와 상관없이 제공할 수 있음
- 매개값들은 자동으로 배열 항목으로 변환되어 메소드에서 사용됨
출처, 이것이 자바다
package ch06.sec08.exam02;
public class Computer {
//가변인수 : 배열과 같은 특징이 있다.
//매개변수의 개수에 상관없이 받을수 있다.
//제공된 매개변수의 누적된 합을 구하는 기능
int sum(int... values) {
int sum = 0;
for(int i=0; i<values.length; i++) {
sum += values[i];
}
// values[0] = 10;
return sum;
}
}
package ch06.sec08.exam02;
public class ComputerExample {
public static void main(String[] args) {
Computer myCom = new Computer();
int result1 = myCom.sum(1, 2, 3);
System.out.println("result1: " + result1);
int result2 = myCom.sum(1, 2, 3, 4, 5);
System.out.println("result2: " + result2);
//int형 배열도 제공
int[] values = {1, 2, 3, 4, 5};
//매소드 호출시 참조타입 변수를 사용하면, 주소가 넘어간다.
int result3 = myCom.sum(values);
System.out.println("result3: " + result3);
//Computer 클래스의 values[0] 주섯처리 변경하여, 값 확인
System.out.println("values[0]: " + values[0]);
int result4 = myCom.sum(new int[] {1,2, 3, 4, 5});
System.out.println("result4: " + result4);
}
}
package ch06.sec08.exam02_1;
public class ArrayReferences {
//1, 2, 3, 4, 5
void arrayValueChange(int[] arr) {
for(int i=0; i<arr.length; i++) {
arr[i] = arr[i] * 10;
}
}
}
package ch06.sec08.exam02_1;
public class ArrayReferencesExample {
public static void main(String[] args) {
//참조타입의 배열변수는 힙영역의 메모리 주소를 가지고 있다.
ArrayReferences arr = new ArrayReferences();
int[] values = {1, 2, 3, 4, 5};
for(int i=0; i<values.length; i++) {
System.out.print(values[i] + " ,");
}
System.out.println();
arr.arrayValueChange(values);
for(int i=0; i<values.length; i++) {
System.out.print(values[i] + " ,");
}
System.out.println();
//주소대입
int[] values2 = values;
for(int i=0; i<values.length; i++) {
System.out.print(values[i] + " ,");
}
}
}
return 문
- 메소드의 실행을 강제 종료하고 호출한 곳으로 돌아간다는 의미
- 메소드 선언에 리턴 타입이 있을 경우에는 return 문 뒤에 리턴값을 추가로 지정해야 함
출처, 이것이 자바다
- return 문 이후에 실행문을 작성하면 ‘Unreachable code’라는 컴파일 에러가 발생
package ch06.sec08.exam03;
public class Car {
//필드선언
int gas;
void setGas(int gas) {
this.gas = gas;
}
boolean isLeftGas() {
if(gas == 0) {
System.out.println("gas가 없습니다.");
return false;
}
System.out.println("gas가 있습니다.");
return true;
}
void run() {
while(true) {
if(gas > 0) {
System.out.println("달립니다. (gas잔량:" + gas + ")");
gas -= 1;
}else {
System.out.println("멈춥니다. (gas잔량:" + gas + ")");
return;
}
}
}
}
package ch06.sec08.exam03;
public class CarExample {
public static void main(String[] args) {
Car myCar = new Car();
//필드사용
// myCar.gas = -5;
//메소드사용
myCar.setGas(5);
// System.out.println("gas: " + myCar.gas);
//gas 유무상태
if(myCar.isLeftGas()) {
System.out.println("출발합니다.");
myCar.run();
}
System.out.println("gas를 주입하세요.");
}
}
메소드 오버로딩
- 메소드 이름은 같되 매개변수의 타입, 개수, 순서가 다른 메소드를 여러 개 선언하는 것
출처, 이것이 자바다
package ch06.sec08.exam04;
/*
* 메소드 오버로딩(중복정의) : 하나의 클래스안에서 메소드명을 중복정의가 가능하도록 하는 문법.
*/
public class Carculator {
//정사각형의 넓이
double areaRectange(double width) {
return width * width;
}
//직사각형의 넓이
double areaRectange(double width, double height) {
return width * height;
}
}
package ch06.sec08.exam04;
public class CarculatorExample {
public static void main(String[] args) {
Carculator myCalcu = new Carculator();
//정사각형의 넓이 구하기 메소드호출
double result1 = myCalcu.areaRectange(10);
//직사각형의 넓이 구하기 메소드호출
double result2 = myCalcu.areaRectange(10, 20);
System.out.println("정사각형의 넓이: " + result1);
System.out.println("직사각형의 넓이: " + result2);
}
}
'객체 지향 프로그래밍 - 클래스' 카테고리의 다른 글
정적 멤버 (0) | 2023.01.16 |
---|---|
인스턴스 멤버 (0) | 2023.01.16 |
생성자 선언과 호출 (0) | 2023.01.16 |
필드 선언과 사용 (0) | 2023.01.16 |
객체와 클래스, 클래스 선언, 객체 생성과 클래스 변수, 클래스의 구성 멤버 (0) | 2023.01.16 |