[Java] Static 메서드1
static 이 붙은 메서드를 알아보자.
특정 문자열을 꾸며주는 간단한 기능을 만들 것이다.
예를 들어 "hello" 라는 문자를 꾸미면 앞 뒤에 *을 붙여서 "*hello*" 와 같이 꾸며주는 기능이다.
인스턴스 메서드
package static2;
public class DecoMain1 {
public static void main(String[] args) {
String s = "Hello World";
Decoutil1 utils = new Decoutil1();
String deco = utils.deco(s);
//s는 hello world
System.out.println("before" + s);
//s을 넣어 deco 메서드 틀에 넣으면 s의 값을 string 으로 받아드리고 ** 사이에 넣는다.
System.out.println("after" + deco);
}
}
package static2;
public class Decoutil1 {
public String deco(String str) {
String result = "*" + str + "*";
return result;
}
}
deco() 메서드는 단순하게 값을 저장해서 호출하는 것 박에 없다.
package static2;
public class DecoMain1 {
public static void main(String[] args) {
String s = "Hello World";
//정적 메서드를 사용하여 클래스.메서드명 으로 하여 바로 호출해서 사용하였다
String deco = Decoutil1.deco(s);
//s는 hello world
System.out.println("before" + s);
//s을 넣어 deco 메서드 틀에 넣으면 s의 값을 string 으로 받아드리고 ** 사이에 넣는다.
System.out.println("after" + deco);
}
}
package static2;
public class Decoutil1 {
public static String deco(String str) {
String result = "*" + str + "*";
return result;
}
}
static을 추가하여 바로 호출하여 사용한 모습이다.
Static 메서드는 static만 사용할 수 있다.
같은 클래스 레벨이면 클래스에서 클래스를 호출할 수 있다.
그러나, static이 없는 인스턴스변수, 인스턴스 메서드의 접근은 불가능하다.
Static 영역에서 힙영역에 있는 값을 불러드릴 수 없다.
Main() 메서드는 정적 메서드
main() 메서드는 프로그램을 시작하는 시작점이 되는데, 생각해보면 객체를 생성하지 않아도 main() 메서드가 작동했다.
이는 main() 은 정적메서드이기 때문이다.
문제와 풀이
문제1: 구매한 자동차 수
다음 코드를 참고해서 생성한 차량 수를 출력하는 프로그램을 작성하자.
`Car` 클래스를 작성하자.
CarMain
package static2;
public class CarMain {
public static void main(String[] args) {
Car car1 = new Car("K3");
Car car2 = new Car("G80");
Car car3 = new Car("Model Y");
Car.showTotalCars(); //구매한 차량 수를 출력하는 static 메서드 }
}
}
실행결과
차량 구입, 이름: K3
차량 구입, 이름: G80
차량 구입, 이름: Model Y
구매한 차량 수: 3 ```
정답
package static2;
public class CarMain {
public static void main(String[] args) {
Car car1 = new Car("K3");
Car car2 = new Car("G80");
Car car3 = new Car("Model Y");
Car.showTotalCars(); //구매한 차량 수를 출력하는 static 메서드 }
}
}
package static2;
public class Car {
private static int totalcats;
private String carname;
int count;
public Car(String carname) {
System.out.println("차량 이름" + carname);
this.carname = carname;
totalcats++;
}
public static void showTotalCars() {
System.out.println("전체 주문한 총 차: " + totalcats );
}
}
totalcats 오타;;
문제2: 수학 유틸리티 클래스
다음 기능을 제공하는 배열용 수학 유틸리티 클래스( `MathArrayUtils` )를 만드세요.
`sum(int[] array)` : 배열의 모든 요소를 더하여 합계를 반환합니다. `average(int[] array)` : 배열의 모든 요소의 평균값을 계산합니다. `min(int[] array)` : 배열에서 최소값을 찾습니다.
`max(int[] array)` : 배열에서 최대값을 찾습니다.
**요구사항**
`MathArrayUtils` 은 객체를 생성하지 않고 사용해야 합니다. 누군가 실수로 `MathArrayUtils` 의 인스턴스를 생성하지 못하게 막으세요. 실행 코드에 `static import` 를 사용해도 됩니다.
실행 결과** ```
sum=15
average=3.0
min=1
max=5
package static2;
public class MathArrayUtilsMain {
public static void main(String[] args) {
int[] values = {1, 2, 3, 4, 5};
System.out.println("sum=" + MathArrayUtils.sum(values));
System.out.println("average=" + MathArrayUtils.average(values));
System.out.println("min=" + MathArrayUtils.min(values));
System.out.println("max=" + MathArrayUtils.max(values));
}
}
package static2;
public class MathArrayUtils {
private MathArrayUtils() {
//private 를 사용하면서 인스턴스 생성을 막는다.
}
public static int sum(int[] values) {
int total = 0;
for (int value : values) {
total += value;
}
return total;
}
public static int average(int[] values) {
return (double) sum(values) / values.length;
}
public static int min(int[] values) {
int min = values[0];
for (int value : values) {
if (value < min) {
min = value;
}
}
return min;
}
public static int max(int[] values) {
int max = values[0];
for (int value : values) {
if (value > max) {
max = value;
}
}
return max;
}
}