SW/HTML

Java : 자바 정적 키워드 : 개념, 개요, 설명, 예제

얇은생각 2023. 2. 27. 07:30
반응형

Java : 자바 정적 키워드 : 개념, 개요, 설명, 예제

 

 

Java 정적 키워드

Java static 키워드는 주로 메모리 관리에 사용됩니다. 변수, 메서드, 블록 및 중첩 클래스를 사용하여 정적 키워드를 적용할 수 있습니다. static 키워드는 클래스의 인스턴스가 아닌 클래스에 속합니다.

 

정적 선언이 가능한 개념

- 변수(클래스 변수)

- 메서드(클래스 메서드)

- 블록

- 중첩 클래스

 

 

 

1) Java 정적 변수

변수를 정적 변수로 선언하면 정적 변수라고 합니다.

정적 변수는 직원 회사 이름, 학생 대학 이름 등과 같이 모든 개체의 공통 속성(각 개체마다 고유하지 않음)을 참조하는 데 사용할 수 있습니다.

정적 변수는 클래스 로드 시 클래스 영역에서 한 번만 메모리를 가져옵니다.

정적 변수의 장점입니다.

프로그램 메모리를 효율적으로 만듭니다. , 메모리를 절약합니다.

정적 변수 없이 문제를 이해합니다.

class Student{  
     int rollno;  
     String name;  
     String college="ITS";  
}

 

 

대학에 500명의 학생이 있다고 가정하면, 이제 모든 인스턴스 데이터 구성원은 개체가 생성될 때마다 메모리를 갖게 됩니다. 모든 학생은 고유한 롤노와 이름을 가지고 있기 때문에 인스턴스 데이터 멤버가 좋습니다. 여기서 "대학"은 모든 객체의 공통 속성을 의미합니다. 이 필드를 정적 상태로 만들면 이 필드는 메모리를 한 번만 가져옵니다.

Java 정적 속성은 모든 개체에 공유됩니다.

정적 변수의 예제입니다.

//Java Program to demonstrate the use of static variable  
class Student{  
   int rollno;//instance variable  
   String name;  
   static String college ="ITS";//static variable  
   
   //constructor  
   Student(int r, String n){  
   rollno = r;  
   name = n;  
   }  
   
   //method to display the values  
   void display (){System.out.println(rollno+" "+name+" "+college);}  
}  

//Test class to show the values of objects  
public class TestStaticVariable1{  
 public static void main(String args[]){  
 Student s1 = new Student(111,"Karan");  
 Student s2 = new Student(222,"Aryan");  
 
 //we can change the college of all objects by the single line of code  
 //Student.college="BBDIT";  
 s1.display();  
 s2.display();  
 }  
}

 

Java : 자바 정적 키워드 : 개념, 개요, 설명, 예제 2

 

 

 

정적 변수가 없는 카운터의 프로그램

이 예제에서는 생성자에서 증가하는 count라는 인스턴스 변수를 만들었습니다. 인스턴스 변수는 객체 생성 시 메모리를 얻기 때문에 각 객체는 인스턴스 변수의 복사본을 가집니다. 이 값이 증가하면 다른 개체를 반영하지 않습니다. 따라서 각 개체는 카운트 변수의 값 1을 가집니다.

//Java Program to demonstrate the use of an instance variable  
//which get memory each time when we create an object of the class.  
class Counter{  
	int count=0;//will get memory each time when the instance is created  
  
    Counter(){  
        count++;//incrementing value  
        System.out.println(count);  
    }  
  
    public static void main(String args[]){  
        //Creating objects  
        Counter c1=new Counter();  
        Counter c2=new Counter();  
        Counter c3=new Counter();  
    }  
}

 

 

정적 변수에 의한 카운터 프로그램입니다.

위에서 언급했듯이, 정적 변수는 메모리를 한 번만 얻을 것이고, 어떤 객체가 정적 변수의 값을 변경하더라도 그 값을 유지할 것입니다.

//Java Program to illustrate the use of static variable which  
//is shared with all objects.  
class Counter2{  
	static int count=0;//will get memory only once and retain its value  
  
    Counter2(){  
        count++;//incrementing the value of static variable  
        System.out.println(count);  
    }  
  
    public static void main(String args[]){  
        //creating objects  
        Counter2 c1=new Counter2();  
        Counter2 c2=new Counter2();  
        Counter2 c3=new Counter2();  
    }  
}

 

 

 

2) 자바 정적 메서드

임의의 메서드에 static 키워드를 적용하면 정적 메서드라고 합니다.

- 정적 메서드는 클래스의 개체가 아니라 클래스에 속합니다.

- 클래스의 인스턴스를 만들지 않고도 정적 메서드를 호출할 수 있습니다.

- 정적 메서드는 정적 데이터 멤버에 액세스할 수 있으며 해당 멤버의 값을 변경할 수 있습니다.

 

정적 방법의 예제입니다.

//Java Program to demonstrate the use of a static method.  
class Student{  
     int rollno;  
     String name;  
     static String college = "ITS";  
     
     //static method to change the value of static variable  
     static void change(){  
     college = "BBDIT";  
     }
     
     //constructor to initialize the variable  
     Student(int r, String n){  
     rollno = r;  
     name = n;  
     }
     
     //method to display values  
     void display(){System.out.println(rollno+" "+name+" "+college);}  
}  

//Test class to create and display the values of object  
public class TestStaticMethod{  
    public static void main(String args[]){  
    Student.change();//calling change method  
    
    //creating objects  
    Student s1 = new Student(111,"Karan");  
    Student s2 = new Student(222,"Aryan");  
    Student s3 = new Student(333,"Sonoo");  
    
    //calling display method  
    s1.display();  
    s2.display();  
    s3.display();  
    }  
}

 

 

정규 계산을 수행하는 정적 방법의 다른 예제입니다.

//Java Program to get the cube of a given number using the static method  
  
class Calculate{  

  static int cube(int x){  
	  return x*x*x;  
  }  
  
  public static void main(String args[]){  
      int result=Calculate.cube(5);  
      System.out.println(result);  
  }  
}

 

 

정적 방법에는 두 가지 주요 제한이 있습니다. 다음과 같습니다.

정적 메서드는 비정적 데이터 멤버를 사용하거나 직접 비정적 메서드를 호출할 수 없습니다.

정적 컨텍스트에서는 이 및 super를 사용할 수 없습니다.

class A{  
 int a=40;//non static  
   
 public static void main(String args[]){  
  System.out.println(a);  
 }  
}

 

 

Q) Java 메인 메서드가 정적인 이유는 무엇입니까?

Ans) 정적 메서드를 호출하는 데 개체가 필요하지 않기 때문입니다. 정적이지 않은 방법인 경우 JVM이 먼저 개체를 생성한 다음 main() 메서드를 호출하여 추가 메모리 할당 문제를 해결합니다.

 

 

3) Java 정적 블록

정적 데이터 멤버를 초기화하는 데 사용됩니다.

클래스 로드 시 주 메서드보다 먼저 실행됩니다.

 

 

정적 블록의 예제입니다.

class A2{  
  static{System.out.println("static block is invoked");}  
  
  public static void main(String args[]){  
   System.out.println("Hello main");  
  }  
}

 

 

Q) main() 메서드 없이 프로그램을 실행할 수 있습니까?

Ans) 아니요, 방법 중 하나는 정적 블록이었지만 JDK 1.6까지는 가능했습니다. JDK 1.7부터는 주 메서드 없이 Java 클래스를 실행할 수 없습니다.

class A3{  
  static{  
      System.out.println("static block is invoked");  
      System.exit(0);  
  }  
}

 

반응형