-
[JAVA] staticProgramming🧑💻/Java 2022. 10. 21. 10:44
static
- static 키워드는 메모리 관리에 사용한다.
- static 키워드를 통해 선언된 변수나 메서드는 클래스내에서 공유된다.
- static 키워드를 사용하면 클래스를 통해 생성한 객체가 아닌 클래스 단에 속한다.
- 클래스를 통해서 만들어진 객체들이 모두 공유하는 필드나 메서드는 static을 이용한다.
1. static member
- member을 static을 이용하여 선언하면 객체를 생성할 필요 없이 직접 접근이 가능하다.
- 원래 클래스의 필드나 메서드에 접근하기 위해서는 생성된 객체를 통해야한다.
class Test { // static method static void m1() { System.out.println("from m1"); } public static void main(String[] args) { // main method는 Test class 내에 속하기 때문에 // static으로 선언된 method는 객체를 만들어 이를 통한 호출이 아닌 // 직접 호출하는 것이 가능하다. m1(); } } // output // from m1
2. static block
- static으로 선언된 변수를 활용할 경우 static block을 이용한다.
class Test { // static variable static int a = 10; static int b; // static block // static 변수인 b에 할당할 값에 대한 계산이 필요할 때 // static block을 이용. static { System.out.println("Static block initialized."); b = a * 4; } public static void main(String[] args) { System.out.println("from main"); System.out.println("Value of a : "+a); System.out.println("Value of b : "+b); } } // output // Static block initialized. // from main // Value of a : 10 // Value of b : 40
3. static variable
- 변수가 static으로 선언되면 해당 변수의 단일 복사본이 생성되어 같은 class의 모든 객체에서 공유되어 사용된다.
- 따라서 class의 모든 객체가 공유하는 global 변수가 필요할 때는 static을 통해 선언한다.
- static 변수와 static block은 프로그램 내에서 작성된 순서에 따라 실행된다.
class Test { // static variable // a 읽어짐에 따라 m1()을 호출 -3 static int a = m1(); // static block // 프로그램 순서에 따라 static block 실행 -5 static { System.out.println("Inside static block"); } // static method // 호출된 m1()이 20을 return하여 a에 값 할당 -4 static int m1() { System.out.println("from m1"); return 20; } // static method(main !!) // 프로그램이 시작되면 main method을 호출 -1 public static void main(String[] args) { // static 변수인 a를 읽음 -2 System.out.println("Value of a : "+a); // 읽어온 a를 출력 -6 System.out.println("from main"); // 나머지 String 출력 -7 } } // output // from m1 // Inside static block // Value of a : 20 // from main
4. static method
- method를 static으로 선언하면 해당 method를 호출하기 위해서 객체를 생성할 필요 없이 같은 class내에서는 직접 호출이 가능
- static method 제약사항
1. static method내에는 오직 다른 static method만 호출이 가능하다.
2. static method는 오직 static data만 직접 접근이 가능하다.
3. this,super keyword를 사용하지 못한다.
class Test { // static variable static int a = 10; // instance variable int b = 20; // static method static void m1() { a = 20; System.out.println("from m1"); // static method은 instance 변수에 값을 할당하지 못한다. b = 10; // compilation error // static method는 non-static method를 호출하지 못한다. m2(); // compilation error // static method는 super keyword을 사용하지 못한다. System.out.println(super.a); // compiler error } // instance method void m2() { System.out.println("from m2"); } public static void main(String[] args) { // main method } }
Static 변수와 메서드는 언제 사용하는가?
- 모든 객체가 공통적으로 가지는 속성에 대해서 static 변수를 사용한다.
- static 변수에 대한 작업이 필요한 경우 static method를 이용한다.
// 같은 학급의 학생들을 나타내는 class class Student { // 이름과 출석번호는 학생마다 다른 고유의 속성이므로 // instance variable로 선언 String name; int rollNo; // 학교 이름은 모든 학생이 동일하므로 // static variable로 선언 static String cllgName; // 학생 객체를 생성할 때마다 // 학급 class의 전체 학생인원수가 증가하므로 // static으로 선언 및 // 이를 이용하여 학생들의 출석번호 부여 static int counter = 0; public Student(String name) { this.name = name; // 학생 객체를 생성할때마다 setRollNO()호출 // setRollNo()가 static 으로 선언되어 // 같은 class 내에서 객체 생성없이 직접 호출 가능 this.rollNo = setRollNo(); } // static 변수인 counter를 이용하는 static method // 호출할 될때마다 counter 변수 1증가 시켜 // 해당 값을 return // 따라서 학생들은 고유한 출석번호를 갖게 됨 static int setRollNo() { counter++; return counter; } // static method // static variable인 cllgName을 set // static variable이기 때문에 this 없이(객체통할필요없이) // 변수에 직접 할당 //(*static method는 객체를 통하지 않고 호출되기 때문에 // 호출한 객체를 가리키는 this keyword 사용 불가*) static void setCllg(String name) { cllgName = name; } // instance method // instance variable는 this를 이용 객체를 통해 접근 // static varable은 직접 접근 void getStudentInfo() { System.out.println("name : " + this.name); System.out.println("rollNo : " + this.rollNo); // accessing static variable System.out.println("cllgName : " + cllgName); } } // Driver class public class StaticDemo { public static void main(String[] args) { // static method를 다른 class에서 호출할때 // classname.staticMethod Student.setCllg("XYZ"); Student s1 = new Student("Alice"); Student s2 = new Student("Bob"); s1.getStudentInfo(); s2.getStudentInfo(); } }
static class
- class에 static을 사용하기 위해서는 해당 class가 nested class(다른 class내의 class)이어야만 한다.
- static class로 선언되면 해당 class 객체 생성시 outerClass의 객체를 통하지 않고 객체를 생성할 수 있게 된다.
- static method와 같이 static class는 outerClass의 non-static member에 접근하지 못한다.
public class GFG { private static String str = "GeeksforGeeks"; // Static class static class MyNestedClass { // non-static method public void disp(){ System.out.println(str); } } public static void main(String args[]) { // static class이기 때문에 outer class의 객체필요없이 // inner class가 직접 객체 생성이 가능 GFG.MyNestedClass obj = new GFG.MyNestedClass(); // non-static method이므로 inner class의 객체를 통해 // 접근해야한다. obj.disp(); } }
'Programming🧑💻 > Java' 카테고리의 다른 글
[JAVA] 컴퓨터와 자바 메모리에 대한 이해 (0) 2023.03.07 [JAVA] String Constant Pool은 무엇일까? (0) 2022.12.17 [JAVA] final (0) 2022.10.25 [JAVA] Enums (0) 2022.10.08 [JAVA] data type : 원시형과 참조형의 차이 (0) 2022.09.28