본문 바로가기
백엔드/[Java]

[Java] 메소드는 무엇일까

by Sir교수 2023. 6. 5.
728x90

메소드

- 메소드는 객체의 동작에 해당하는 중괄호 { } 블록

- 중괄호 블록 이름이 메소드 이름이고 이 메소드를 호출하면 일괄적으로 실행된다. 

메소드 선언

- 메소드 선언은 선언부(리턴 타입, 메소드 이름, 매개 변수 선언) 과 실행 블록으로 구성

리턴 타입

- 리턴값(메소드를 실행한 후의 결과값)의 타입

- 리턴값이 있을 경우 리턴 타입이 선언부에 명시되어야 한다. 

- 예를 들어 전원 버튼, 나누기 버튼이 있다면 전원 메소드는 리턴값이 없고, 나누기 메소드는 나눈 값이 리턴값이다.

- 리턴값이 없는 메소드는 리턴 타입에 void로 기술, 리턴값이 없어서 변수에 저장할 내용이 없어 메소드만 호출 

 

Calculator 클래스에서 powerOn(), plus(), divide(), powerOff() 메소드를 선언

package ex;

public class Calculator {

  //메소드
    void powerOn() {
    System.out.println(" 전원을 on");
 }
 
 int plus(int x,int y) {
   int result = x + y;
   return result;
}

double divide(int x, int y ) {
  double result = (double)x / (double)y;
  return result;
}

void powerOff() {
  System.out.println(" 전원을 off");
  }

}

- 외부 클래스에서 Calculator 클래스의 메소드를 호출하기 위해서는 Calculator 객체를 생성하고

- 참조 변수인 myCalc를 이용해야 한다. myCalc 변수에 도트와 함께 메소드이름 형태로 호출 

package ex

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);
    
    byte x = 10;
    byte y = 4;
    double result2 = myCalc.divide(x, y);
    System.out.println("result2: " + result2);
    myCal.powerOff();
    }
}

Return문 void문

package 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 exam03;

public class CarExample {
	public static void main(String[] args) {
		Car myCar = new Car();
		
		myCar.setGas(5);
		
		boolean gasState = myCar.isLeftGas();
		if(gasState) {
			System.out.println("출발합니다.");
			myCar.run();
		}
		
		if(myCar.isLeftGas()) {
			System.out.println("gas를 주입할 필요가 없습니다.");
		}   else {
			System.out.println("gas를 주입하세요.");
		}
	}
}

 

728x90

'백엔드 > [Java]' 카테고리의 다른 글

[Java] 인스턴스, static?  (0) 2023.06.06
[Java] 객체 지향 프로그래밍, 생성자  (0) 2023.06.03
[Java] 기초  (0) 2023.06.01