초급과정/java

[Java] 스태틱 (Static)

whalerice 2023. 10. 19. 18:39

 

public class StaticMain {
	public static void main(String[] args) {
		int a = StaticTest.a;
		StaticTest.method2();
		
		//Static을 선언하지 않은 것은 이렇게 불러와야 함 위 코드보다 불편.
		//Static을 남발하면 안되는 이유: 누군가가 건드렸을때 값이 변하기때문에 고정된 값 쓰기 힘듦 
		StaticTest st = new StaticTest();
		int b = st.b;
		st.method1();
	}
}
public class StaticTest {
	static int a = 10;
	       int b = 10;

	public static void main(String[] args) {
		
		StaticTest s1 =new StaticTest();
		System.out.println("static int a\t"+a);
		System.out.println("       int b\t"+s1.b);
		
		a = 20;
		s1.b = 15;
		
		System.out.println("변경 후 값");
		System.out.println("static int a\t"+a);
		System.out.println("       int b\t"+s1.b);
		
		StaticTest s2 =new StaticTest();
		System.out.println("static int a\t"+a);
		System.out.println("       int b\t"+s2.b);
		
		StaticTest s3 =new StaticTest();
		System.out.println("static int a\t"+a);
		System.out.println("       int b\t"+s3.b);
		
		
		StaticTest st = new StaticTest();
		st.b = 20;
		st.method1();
		
		//static = 메모리 부분에 이미 호출할 수 있도록 올라가있어서 바로 부를수 있다. 
		method2();
		
		StaticTest st2 = new StaticTest();
		st2.method1();
		
		
	}
	
	public void method1() {
		System.out.println("public void method1() 호출");
		System.out.println("static int a\t"+a);
		// 객체가 만들어졌을때의 b 값 
		System.out.println("       int b\t"+b);
	}
	
	public static void method2() {
		System.out.println("public static void method2() 호출");
		System.out.println("static int a\t"+a);

	}
}