Computer >> 컴퓨터 >  >> 프로그램 작성 >> Android

Kotlin의 Java 정적 메소드와 동일한 것은 무엇입니까?


자바에서는 효율적인 메모리 관리를 위해 "정적" 키워드가 사용됩니다. 변수 또는 메서드가 정적으로 선언되면 , JVM은 이러한 변수에 대해 한 번만 메모리를 할당합니다. 일반적으로 정적 변수는 클래스의 공통 속성을 선언하는 데 사용됩니다. (예:"기관 이름"). 다음 예에서는 정적 키워드.

Java 사용 시 Static 예제

정적 Java에서 작동하는 경우 온라인 Java 컴파일러에 액세스하고 테스트 수업. 테스트 내부 , 우리는 정적 메소드를 사용하면 클래스를 생성하지 않고 두 가지 모두에 액세스할 수 있습니다. 개체.

예시

public class Test
{
   static int myStaticVariable = 10;
   // static method
   static void staticMethod()
   {
      System.out.println("www.tutorialspoint.com");
   }

   public static void main(String[] args)
   {

      // accessing static method and variable without creating
      // any object of class Test
      staticMethod();
      System.out.println("Accessing Static variable-"+myStaticVariable);
   }
}

출력

코드를 실행하면 다음과 같은 출력이 생성됩니다. -

$javac Test.java
$java -Xmx128M -Xms16M Test
www.tutorialspoint.com
Accessing Static variable-10

Kotlin의 Java 정적 메소드와 동일

Kotlin에는 정적이 없습니다. 예어. 이 기사에서는 Kotlin 라이브러리에서 사용할 수 있는 다른 키워드를 사용하여 동일한 메모리 관리를 달성하는 방법을 배웁니다. 목표는 메모리가 한 번만 생성되고 해당 값을 애플리케이션의 다른 섹션에서 수정할 수 없는 조건을 선택하도록 다른 Kotlin 라이브러리 함수를 구현하는 것입니다.

정적을 사용하는 두 가지 방법이 있습니다. 코틀린에서 -

  • 컴패니언 개체 사용

  • 객체 클래스 및 @JvmStatic 주석 사용

각각의 방법을 자세히 알아봅시다.

컴패니언 개체 사용

컴패니언 추가 개체에서 개발자가 정적을 달성하는 데 도움이 됩니다. 코틀린의 기능. 클래스가 저장된 동일한 파일에 객체를 저장하므로 클래스 내부의 모든 개인 메서드와 변수에 액세스할 수 있습니다. 클래스 초기화 단계와 함께 초기화됩니다.

예시

컴패니언 객체를 구현하려고 시도하고 Kotlin에서 메모리 관리를 얼마나 효율적으로 처리할 수 있는지 확인할 것입니다.

fun main(args: Array<String>) {
   // Accessing class variable and method
   //with out creating class object
   println("Hello!"+'\n' + "This an example of accessing class variable without creating object." + MyClass.staticField+'\n')
   println("Hello!"+'\n' + "This an example of accessing class Method without creating an object." + MyClass.getStaticFunction()+'\n');

}

class MyClass{
   companion object {
      val staticField = "This is a Static Variable."
      fun getStaticFunction(): String {
         return "This is a static Method."
      }
   }
}

출력

코드를 실행하면 다음과 같은 출력이 생성됩니다. -

Hello!
This an example of accessing class variable without creating
object. This is a Static Variable.

Hello!
This an example of accessing class Method without creating an
object. This is a static Method.

이 샘플 코드에서 정적 변수를 사용하면 Kotlin 컴파일러에서 오류가 발생하는 것을 볼 수 있습니다.

예시

fun main(args: Array) {

   // Trying to modify the static variable

   MyClass.staticField="Hello Students";
   println("Hello!"+'\n'+"This an example of accessing class variable with out creating object-"+MyClass.staticField+'\n')

}
class MyClass{
   companion object {
      val staticField = "This is an Static Variable"
      fun getStaticFunction(): String {
         return "This is a static Method"
      }
   }
}

출력

위의 코드는 다음 오류를 생성합니다 -

$kotlinc -nowarn main.kt -include-runtime -d main.jar
main.kt:5:5: error: val cannot be reassigned
MyClass.staticField="Hello Students";
^

객체 클래스 및 @JvmStatic 주석 사용

Kotlin 문서에 따라 @JvmStatic 한 번 주석은 모든 변수 또는 메서드에 적용되며 정적으로 작동합니다. 해당 클래스의 기능입니다.

예시

다음 예에서는 객체를 생성합니다. 클래스 및 해당 객체에서 클래스에서 @JvmStatic을 사용하여 변수와 메서드를 선언합니다. 정적을 구현하기 위한 주석 Kotlin 환경의 기능

fun main(args: Array) {
   // Accessing class variable and method
   //with out creating class object
   println("Hello!"+'\n' + "This an example of accessing a class variable without creating an object." +MyClass.staticField+'\n')
   println("Hello!"+'\n' + "This an example of accessing a class Method without creating an object. " +MyClass.getStaticFunction()+'\n');

}
object MyClass{
   @JvmStatic
   val staticField = "This is a Static Variable."
   @JvmStatic
   fun getStaticFunction(): String {
      return "This is a Static Method."
   }
}

출력

결과 섹션에 다음 출력이 생성됩니다. -

Hello!
This an example of accessing class variable without creating
object. This is a Static Variable.

Hello!
This an example of accessing class Method without creating an
object. This is a static Method.