JAVA

221013 static 실습

주영재 2022. 10. 13. 12:14

※자바에서 static에 대해 알아둬야 할 것
1. static멤버는 객체 생성 없이 "클래스명.이름"으로 참조 가능하다
->"클래스명.이름"이면 static이라고 판단할 것
2.static변수는 객체간 값의 공유의 의미
3.static메서드는 같은 static멤버만 참조 가능하다.
->마찬가지로 클래스명.이름으로 참조한다.

 

package day08.static_.basic;

public class PrintArray {
	
	private PrintArray() {}//객체생성불가

	public static String toArray(int[] a){
		String answer="[";
		for(int i=0;i<a.length;i++) {
			if(i<a.length-1) {
				answer+=a[i]+", ";
			}
			else if(i==a.length-1) {
				answer+=a[i]+"]";
			}
		}
		return answer;
	}
	
	public static String toArray(char[] c) {
		String answer="[";
		for(int i=0;i<c.length;i++) {
			if(i<c.length-1) {
				answer+=c[i]+", ";
			}
			else if(i==c.length-1) {
				answer+=c[i]+"]";
			}
		}
		return answer;
	}
	
	public static String toArray(String[] s) {
		String answer="[";
		for(int i=0;i<s.length;i++) {
			if(i<s.length-1) {
				answer+=s[i]+", ";
			}
			else if(i==s.length-1) {
				answer+=s[i]+"]";
			}
		}
		return answer;
	}
	
}

 

main

package day08.static_.basic;

import java.util.Arrays;

public class MainClass {
	public static void main(String[] args) {
		//PrintArray parr = new PrintArray();
		
		
		int[] arr= {1,2,3,4,5};
		System.out.println(Arrays.toString(arr));
		System.out.println(PrintArray.toArray(arr));
		
		char[] crr = {'a','b','c','d'};
		System.out.println(PrintArray.toArray(crr));
		
		String[] srr = {"안", "녕", "하", "세", "요"};
		System.out.println(PrintArray.toArray(srr));
	}

}
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[a, b, c, d]
[안, 녕, 하, 세, 요]

객체를 생성하지 않고도 메서드를 static으로 만들어 클래스로 호출하여 같은 static인 메인에서 사용하는 것이 가능함