logo

Java 정적 키워드

  1. 정적 변수
  2. 정적 변수가 없는 카운터 프로그램
  3. 정적 변수를 사용한 카운터 프로그램
  4. 정적 방법
  5. 정적 메서드에 대한 제한 사항
  6. 주요 메소드가 왜 정적인가요?
  7. 정적 블록
  8. main 메소드 없이 프로그램을 실행할 수 있나요?

그만큼 정적 키워드 ~에 자바 주로 메모리 관리에 사용됩니다. 정적 키워드를 적용할 수 있습니다. 변수 , 메소드, 블록 및 중첩 클래스 . static 키워드는 클래스의 인스턴스가 아닌 클래스에 속합니다.

추상 수업

정적은 다음과 같습니다.

  1. 변수(클래스 변수라고도 함)
  2. 메서드(클래스 메서드라고도 함)
  3. 차단하다
  4. 중첩 클래스
Java의 정적

1) 자바 정적 변수

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

  • 정적 변수는 직원의 회사 이름, 학생의 대학 이름 등과 같이 모든 개체의 공통 속성(각 개체에 대해 고유하지 않음)을 참조하는 데 사용할 수 있습니다.
  • 정적 변수는 클래스 로딩 시 클래스 영역에서 한 번만 메모리를 가져옵니다.

정적 변수의 장점

그것은 당신의 프로그램을 만듭니다 메모리 효율성 (즉, 메모리를 절약합니다).

정적 변수가 없는 문제 이해

 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(); } } 
지금 테스트해보세요

산출:

 111 Karan ITS 222 Aryan ITS 

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

이 예에서는 생성자에서 증가되는 count라는 인스턴스 변수를 만들었습니다. 인스턴스 변수는 객체 생성 시 메모리를 가져오므로 각 객체는 인스턴스 변수의 복사본을 갖게 됩니다. 증가하면 다른 개체가 반영되지 않습니다. 따라서 각 객체는 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(); } } 
지금 테스트해보세요

산출:

알리야 마나사
 1 1 1 

정적 변수에 의한 카운터 프로그램

위에서 언급했듯이 정적 변수는 메모리를 한 번만 가져오며, 객체가 정적 변수의 값을 변경하면 해당 값을 유지합니다.

 //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(); } } 
지금 테스트해보세요

산출:

 1 2 3 

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(); } } 
지금 테스트해보세요
 Output:111 Karan BBDIT 222 Aryan BBDIT 333 Sonoo BBDIT 

일반 계산을 수행하는 정적 메서드의 또 다른 예

 //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); } } 
지금 테스트해보세요
 Output:125 

정적 메서드에 대한 제한 사항

정적 메서드에는 두 가지 주요 제한 사항이 있습니다. 그들은:

자바로 파일을 여는 방법
  1. 정적 메서드는 비정적 데이터 멤버를 사용하거나 비정적 메서드를 직접 호출할 수 없습니다.
  2. this 및 super는 정적 컨텍스트에서 사용할 수 없습니다.
 class A{ int a=40;//non static public static void main(String args[]){ System.out.println(a); } } 
지금 테스트해보세요
 Output:Compile Time Error 

Q) Java 메인 메소드가 왜 정적인가요?

답변) 객체가 정적 메소드를 호출할 필요가 없기 때문입니다. 비정적 메서드인 경우 JVM 먼저 객체를 생성한 다음 추가 메모리 할당 문제를 일으키는 main() 메서드를 호출합니다.


3) 자바 정적 블록

  • 정적 데이터 멤버를 초기화하는 데 사용됩니다.
  • 클래스 로딩 시 메인 메소드보다 먼저 실행됩니다.

정적 블록의 예

 class A2{ static{System.out.println('static block is invoked');} public static void main(String args[]){ System.out.println('Hello main'); } } 
지금 테스트해보세요
 Output:static block is invoked Hello main 

Q) main() 메소드 없이 프로그램을 실행할 수 있나요?

답변) 아니요, 그 방법 중 하나가 static block이었는데, JDK 1.6까지는 가능했습니다. JDK 1.7부터는 Java 클래스 없이는 Java 클래스를 실행할 수 없습니다. 주요 방법 .

 class A3{ static{ System.out.println('static block is invoked'); System.exit(0); } } 
지금 테스트해보세요

산출:

문자열을 int로 변환 java
 static block is invoked 

JDK 1.7 이상부터 출력은 다음과 같습니다.

 Error: Main method not found in class A3, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application