06
23
728x90

리턴(return) 문

메소드의 실행을 중지하고 리턴값을 지정하는 역하을 한다.

return [리턴값];

 

리턴값이 있는 메소드

반드시 리턴(return)문을 사용해서 리턴값을 지정해야 한다.

//int 리턴타입이 지정되어있기 때문에 리턴문을 사용해주어야함
int puls(int x, int y)
{
       int result = x + y;
       return result;
}

return문 뒤에는 실행문이 올 수 없다.

int puls(int x, int y)
{
       int result = x + y;
       return result;
       System.out.println(result);     //Unreachable code
}

 

리턴값이 없는 메소드 (void)

return문은 옵션이며, return문의 용도는 메소드 실행을 단지 중지한다.

void run()
{
       while(true)
       {
                if(gas > 0)
                {
                          System.out.println("달립니다.(gas 잔량:" +  gas + ")");
                          gas -= 1;
                }
                else
                {
                          System.out.println("멈춥니다.(gas 잔량:" +  gas + ")");
                          return;    //run() 메소드 실행 종료 ,
                                      //return 대신에 break; 사용해도됨(while문을 빠져나가는 것이기 때문에)
                }
}

 

예제)

package sec08.exam02_return;

public class Car 
{
	int gas;
	
	void setGas(int gas)
	{
		this.gas = gas;
	}

	boolean isLeftGas() //gas가 있으면 true 없으면 false
	{
		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 = gas-1;
			}
			else
			{
				System.out.println("멈춥니다. (gas잔량:" +gas+")");
				return; //run()이 끝나게됨
			}
		}
	}
}
package sec08.exam02_return;

public class CarExample 
{
	public static void main(String[] args) 
	{
		Car myCar = new Car();
		
		myCar.setGas(5);
		
		boolean gasState = myCar.isLeftGas();
		if(gasState) //gas가 있으면
		{
			System.out.println("출발합니다.");
			myCar.run(); //gas를 다 소비하게됨
		}
		if(myCar.isLeftGas()) //gas가 있으면 실행 , 없으므로 실행되지 않음
		{
			System.out.println("gas를 주입할 필요가 없습니다.");
		}
		else
		{
			System.out.println("gas를 주입하세요.");
		}
	}
}

출력 결과

 

메소드 호출

메소드는 클래스 내/외부의 호출에 의해 실행된다.

클래스 내부 : 메소드 이름으로 호출

클래스 외부 : 객체 생성 후, 참조 변수를 이용해서 호출

 

객체 내부에서 호출

메소드의 이름으로 호출하되, 매개변수의 타입과 수에 맞게 매개값을 제공해야 한다.

리턴값이 없는 메소드 호출

메소드( 매개값, ...);

 

리턴값이 있는 메소드 호출

public class ClassName()
{
       int method1(int x, int y)
       {
                int result = x + y;
                return result;
       }

       void method2()
       {
                int result1 = method1(10,20);         //result1에는 30이 저장
                double result2 = method1(10,20);   //result2에는 30.0이 저장 / 자동타입변환이 이루어짐
       }
}

 

예제)

package sec08.exam03_method_call;

public class Calculator 
{
	int plus(int x, int y)
	{
		int result = x + y;
		return result;
	}
	
	double avg(int x, int y)
	{
		double sum = plus(x,y);  //plus함수 호출 
		double result = sum / 2;
		return result;
	}
	
	void execute()
	{
		double result = avg(7,10); //avg 함수 호출
		println("실행결과 :" + result);
	}
	
	void println(String message)
	{
		System.out.println(message);
	}
}
package sec08.exam03_method_call;

public class CalculatorExample 
{
	public static void main(String[] args) 
	{
		Calculator myCalc = new Calculator();
		
		myCalc.execute();

	}
}

출력 결과

 

객체 외부에서 호출

클래스로부터 객체를 생성하고 클래스 변수가 참조하도록 한다.

클래스 참조변수 = new 클래스(매개값, ...);

참조변수와 함께 도트(.) 연산자를 이용해서 메소드를 호출한다.

도트(.)연산자는 객체 접근 연산자로 객체가 가지고 있는 필드나 메소드에 접근한다.

참조변수.메소드( 매개값, ... );  //리턴값이 없거나, 있어도 리턴값을 받지 않을 경우
타입 변수 = 참조변수.메소드 ( 매개값, ... );  //리턴값이 있고, 리턴값을 받고 싶을 경우
Car myCar = new Car();
myCar.keyTurnOn();
myCar.run();
int speed = myCar.getSpeed();

 

예제)

package sec08.exam03_method_call;

public class Car 
{
	int speed;
	
	int getSpeed()
	{
		return speed;
	}
	
	void keyTurnOn()
	{
		System.out.println("키를 돌립니다.");
	}
	
	void run()
	{
		for(int i= 10; i<=50; i+=10)
		{
			speed = i;
			System.out.println("달립니다. (시속 : " + speed + "km/h)");
		}
	}

}
package sec08.exam03_method_call;

public class CarExample 
{
	public static void main(String[] args) 
	{
		Car myCar = new Car();
		
		myCar.keyTurnOn(); //함수호출
		myCar.run();  //함수호출
		
		myCar.getSpeed();  //함수호출
		
		int speed = myCar.getSpeed();
		
		System.out.println("현재 속도:" + speed + "km/h");
	}
}

출력 결과

 

메소드 오버로딩(Overloading)

클래스 내에 같은 이름의 메소드를 여러 개 선언하는 것을 말한다.

하나의 메소드 이름으로 다양한 매개값을 받기 위해 메소드를 오버로딩한다.

오버로딩의 조건 : 매개변수의 타입, 개수, 순서가 달라야 한다.

매개값을 어떻게 주느냐에 따라 오버로딩된 메소드 중 하나가 선택되어 실행된다.

ex) System.out.println( .... );  //println이 여러개 선언이 되어 있어서 어떤 타입의 값을 넣더라도 잘 실행됨
void println() {...}
void println(boolean x) {...}
void println(char x) {...}
void println(char[] x) {...}
void println(double x) {...}
void println(float x) {...}
void println(int x) {...}
void println(long x) {...}
void println(Object x) {...}
void println(String x) {...}

 

예제)

package sec08.exam04_overloading;

public class Calculator 
{
	double areaRectangle(double width)
	{
		return width * width;
	}
	
	double areaRectangle(double width, double height)
	{
		return width * height;
	}
}
package sec08.exam04_overloading;

public class CalculatorExample 
{
	public static void main(String[] args) 
	{
		Calculator myCalcu = new Calculator();
		
		double result1 = myCalcu.areaRectangle(10); //10이라는 정수값을 넣어주었지만 10.0이라는 double로 변환되어 들어감
		double result2 = myCalcu.areaRectangle(10, 20);
		
		System.out.println("정사각형의 넓이 = " + result1);
		System.out.println("직사각형의 넓이 = " + result2);
	}
}

출력 결과

 

728x90
COMMENT