개발도생's Blog
[9Days] Study_Method 본문
많이 사용하면서 잘 모르는 부분이라 공부해 봤다.
Method란,
자바에서 클래스는 멤버(member)로 속성을 표현하는 필드(field)와
기능을 표현하는 메서드(method)가 있다.
메서드(method)란 어떠한 특정 작업을 수행하기 위한 명령문의 집합이라 할 수 있다.
그렇다면, Method는 왜 사용하는가?
클래스에서 메서드를 작성하여 사용하는 이유는,
중복되는 코드의 반복적인 프로그래밍을 피할 수 있기 때문이다.
모듈화로 인해 코드의 가독성을 높이고,
프로그램에 문제가 발생하거나 기능의 변경이 필요할 때도 손쉽게 유지보수를 할 수 있게 됩니다.
Method의 정의는,
public class Class {
public void method() {
// 구현부
}
}
Method를 생성하고 보면 생성자(Constructor)와 유사한 모습이다.
[8Days] Study_Static&Constructor
오늘은 'static' 키워드와 생성자(Constructor)에 대해서 공부해 봤다. 'static' 키워드란, 클래스를 정의할 때 'static 키워드'를 사용한 프로퍼티와 메서드는 해당 클래스의 인스턴스를 생성하지 않아도
nan-o-nuel-do.tistory.com
그리고 중괄호 내부에 고유 기능을 수행하는 명령문을 입력하게 되는데,
그 모든 명령문의 집합이 있는 영역을 '구현부'라고 한다.
public class Method {
public void method() {
/*
* 결과를 반환 후 코드를 종료한다.
* - 결과 반환은 호출한 인스턴스를 통해 반환하게 된다.
*/
System.out.println("반환 타입은 void이고, 매개변수가 없는 Method");
}
}
구현부에 명령문을 입력하고 해당 Method를 호출하게 되면,
구현부에 입력된 명령문이 실행이 돼서 값을 호출한 인스턴스로 돌아가 값을 반환하게 된다.
public class MethodTest {
public static void main(String[] args) {
Method m = new Method();
// Method를 호출
m.method();
}
}
반환 타입을 반드시 'void'를 사용해야 되는 것은 아니다.
void란, 어떠한 값도 반환하지 않는다는 의미이다.
Method는 다양한 반환 타입으로 생성할 수 있고, 사용자가 용도에 맞게 Method를 생성할 수 있다.
또한 매개변수를 통해 값을 입력받아 Method의 구현부에서 활용할 수 있다.
예를 들어, 매개 변수를 배열로 받는다고 했을 때,
public class Method {
public void method(int[] arr) {
System.out.println("반환 타입은 void이고, 매개변수가 배열인 Method");
System.out.println(arr);
}
}
public class MethodTest {
public static void main(String[] args) {
Method m = new Method();
// 같은 참조값을 사용한다.
int[] test01 = new int[] {1, 2, 3};
System.out.println(test01);
m.method(test01);
}
}
배열은 Class에 선언한 배열의 참조값과 Method의 매개변수로 전달받은 배열의 참조값이 같은 걸 확인할 수 있다.
호출한 Method의 매개변수로 값을 받아서 구현부 내부에서 배열의 값을 수정하게 된다면,
Class 내부에 선언했던 배열의 값도 동일하게 변경되는 '얕은 복사'의 결과를 확인하게 된다.
public class Method {
public void method(int[] arr) {
System.out.println("반환 타입은 void이고, 매개변수가 배열인 Method");
System.out.println(arr);
for(int i = 0; i < arr.length; i++) {
arr[i] += 1;
System.out.println("arr[" + i + "] : " + arr[i]);
}
}
}
이렇게 Method를 활용할 수 있다는 것이 객체 지향 언어의 장점 중 하나다.
지금까지 공부한 Method를 활용해 간단한 실습을 해봤다.
먼저 Method를 호출하기 위한 Main Class를 생성해 주고,
public class Main {
public static void main(String[] args) {
/*
* Circle Class, Rectangle Class, Triangle Class를 만든다.
*
* 1. 위의 만들어진 클래스를 이용하여 각 도형의 너비를 구하기 위한 메서드를 만들어 본다.
* (Method 명은 'area'로 한다.)
*
* 2. 위의 만들어진 클래스를 이용하여 각 도형의 둘레를 구하기 위한 메서드를 만들어 본다.
* (Method 명은 'round'로 한다.)
*/
}
}
주석의 내용에 맞게 Class를 생성해 Method를 만들었다.
public class Circle {
public final static double PI = Math.PI;
public double area(double radius) {
return PI * radius * radius;
}
public double round(double radius) {
double result;
result = PI * radius * 2;
return result;
}
}
public class Triangle {
public int area(int base, int height) {
return (base * height) / 2;
}
public int round(int a, int b, int c) {
return a + b + c;
}
}
public class Rectangle {
public int area(int width) {
return (int) Math.pow(width, 2);
}
public int area(int width, int height) {
return width * height;
}
public int round(int width, int height) {
return (width * height) * 2;
}
}
세 개의 Class를 생성하고 해당 Class들 내부에 Method들을 선언한 후, Main Class에서 호출했다.
public class Main {
public static void main(String[] args) {
/*
* Circle Class, Rectangle Class, Triangle Class를 만든다.
*
* 1. 위의 만들어진 클래스를 이용하여 각 도형의 너비를 구하기 위한 메서드를 만들어 본다.
* (Method 명은 'area'로 한다.)
*
* 2. 위의 만들어진 클래스를 이용하여 각 도형의 둘레를 구하기 위한 메서드를 만들어 본다.
* (Method 명은 'round'로 한다.)
*/
Circle circle01 = new Circle();
System.out.printf("원의 너비 : %.2f\n",circle01.area(4.0));
System.out.printf("원의 둘레 : %.2f\n",circle01.round(4.0));
System.out.println("---------------------");
Rectangle rectangle01 = new Rectangle();
System.out.printf("직사각형의 너비 : %d\n", rectangle01.area(5, 6));
System.out.printf("직사각형의 둘레 : %d\n", rectangle01.round(5, 6));
System.out.println("---------------------");
Triangle triangle01 = new Triangle();
System.out.printf("삼각형의 너비 : %d\n", triangle01.area(5, 6));
System.out.printf("삼각형의 둘레 : %d\n", triangle01.round(5, 6, 7));
}
}
위와 같이 Class를 객체로 생성하고 인스턴스를 통해 Method를 호출하게 되면,
결과를 확인할 수 있다.
Method에 대한 지식이 한참은 부족하고, 활용도 많이 부족하다.
그래도 Method를 활용했을 때 모듈화에 대한 이해와, 객체 지향 언어에 대한 이해도가 조금 더 높아진 것 같다.
아직도 배워야 할 것도, 알아가야 할 것도 많지만 즐거운 마음으로 공부할 것이다.
부지런하게 배우고 익혀서 성장할 수 있도록!
'개발자의 일기 > Study' 카테고리의 다른 글
[11Days] Study_추상화 (0) | 2023.04.07 |
---|---|
[10Days] Study_Inheritance (0) | 2023.03.28 |
[8Days] Study_Static&Constructor (0) | 2023.03.22 |
[7Days] Study_객체 지향 언어(Java) (0) | 2023.03.18 |
[6Days] Study_배열(Array) (0) | 2023.03.15 |