ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Java]Static 메서드란? 사용하는 이유
    Java & Kotlin 2020. 4. 18. 13:16
    반응형

    Static 단어의 정의

    프로그래밍 언어는 안타깝게도 전부다 영어입니다.

    그렇기 때문에 영어를 잘한다면 이해를 쉽게 할 수 있습니다.

     

     

     

     

    • 움직임, 변화, 어떤 면에서 흥미가 떨어지게 바라보는
    • 특정 기간, 시간(프로그래밍이 실행 중) 동안 변화할 수 없는

     

    대충 감이 옵니다. 

    뭔가 움직이지 않고, 변하지도 않고 그대~로 있는 느낌입니다.



     

     


    예제 코드

    class remote {
    
        int a; // instance variable
    
        // instance method
        int channelUp() { return a + 1; } // used instance variable
        int channelDown() { return a - 1; }
    
        // static method
        static int channelUp2(int b) { return b + 1; }
        static int channelDown2(int b) {return b - 1; }
    
    }
    
    public class Main {
        public static void main(String[] args) {
    
            // create instance
            remote control = new remote();
            control.a = 10;
    
            // call instance method
            System.out.println("------instance method------");
            System.out.println(control.channelUp());
            System.out.println(control.channelDown());
    
            // call static method
            System.out.println("------static method------");
            System.out.println(remote.channelUp2(10));
            System.out.println(remote.channelDown2(10));
        }
    }

    결괏값



     

     


    인스턴스 메서드(instance method) 과정

    class remote {
    
        int a; // instance variable
    
        // instance method
        int channelUp() { return a + 1; } // used instance variable
        int channelDown() { return a - 1; }
    }
    
    public class Main {
        public static void main(String[] args) {
    
            // create instance
            remote control = new remote();
            control.a = 10;
    
            // call instance method
            System.out.println("------instance method------");
            System.out.println(control.channelUp());
            System.out.println(control.channelDown());
            
    	}
    }

     

    remote 클래스를 생성합니다.

     

    int a → 인스턴스 변수를 생성합니다.

    int channelUp(), channelDwon() → 인스턴스 메서드를 생성합니다.

     

    여기서 return 값으로 사용된 a는 이미 생성된 int a 인스턴스 변수입니다.

    인스턴스 변수를 사용하므로 () 안의 매개변수는 사용하지 않습니다.

     

     

    Main 클래스로 갑니다

     

            remote control = new remote();

     

    클래스를 사용하기 위해서 인스턴스를 생성합니다.

    즉 메모리에 공간을 만드는 과정입니다.

     

    control.a = 10;으로 메모리 주소에 값을 줍니다.

     

    만들어진 객체 변수 control을 사용하여 remote 클래스의 메서드들을 사용합니다.

    channelUp을 하게 되면 10 + 1이 실행되고, 

    channelDown을 하게 되면 10 - 1이 실행됩니다.


    Staic method 과정

    class remote {
    
        // static method
        static int channelUp2(int b) { return b + 1; } // used local variable
        static int channelDown2(int b) {return b - 1; }
    
    }
    
    public class Main {
        public static void main(String[] args) {
    
            // call static method
            System.out.println("------static method------");
            System.out.println(remote.channelUp2(10));
            System.out.println(remote.channelDown2(10));
            
        }
    }

     

    똑같이 remote 클래스에 속합니다.

     

    하지만 다른 점은 static이 추가됩니다.

    여기서 return 값으로 사용된 b는 지역변수(local variable)입니다.

    또한  (int b)와 같은 매개변수가 존재합니다.

     

     

    Main 클래스로 갑니다

     

    여기서 앞의 인스턴스 메서드와 차이점은

    인스턴스 생성 없이 바로 static 메서드를 호출할 수 있습니다.



     

     


    Static

     

    ● 인스턴스 메서드처럼 인스턴스(객체)를 생성할 필요가 없습니다

    왜냐하면 static이 붙은 변수(클래스 변수)는 클래스가 메모리에 올라갈 때 이미 자동적으로 생성됩니다. 즉 메서드 호출시간이 짧아지므로 성능이 향상됩니다.

     

    ● 인스턴스 변수는 static 메서드에서 사용할 수 없습니다

    왜냐하면 인스턴스 변수는 Main 메서드에서 사용할 때 인스턴스(객체)를 생성해야 하기 때문입니다.

     

    ●  인스턴스 변수를 사용하지 않는다면, static 메서드를 사용하는 것이 좋습니다

    왜냐하면 static 메서드는 실행 시 호출되어야 할 메서드를 찾는 과정이 필요 없기 때문에, 속도 면에서 우위에 있습니다.

     

    ●  모든 인스턴스에 공통으로 사용하는 것에 static을 붙입니다

    static 변수 생성 시, 클래스에 대한 인스턴스 2개를 만듭니다. 그 뒤 1개의 인스턴스로 static 변수를 변경하더라도, 나머지 인스턴스도 같이 변경 됩니다.

     

     

    One rule-of-thumb: ask yourself "Does it make sense to call this method, even if no object has been constructed yet?" If so, it should definitely be static.

    "객체가 생성되지도 않았는데, 메서드를 call 할 수 있을까?"라고 스스로 물어봤을 때, 가능하다면 그것은 static일 것입니다.

    출처: https://stackoverflow.com/questions/2671496/java-when-to-use-static-methods?rq=1

     

     

     

     

     

     

    책 "자바의 정석 기초편"과 "Stack Overflow"를 참고했습니다.

     

    *틀린 정보가 있을 시 댓글로 알려주시면 바로 수정하겠습니다!

    **이해가 안 가는 부분도 댓글 남겨주시면 열심히 고민해보고 알려드리겠습니다 

     

     

     

     

     

    반응형

    'Java & Kotlin' 카테고리의 다른 글

    (Java)Math.max vs 삼항연산자  (0) 2021.01.30
    [Java]2차원 배열이란?  (0) 2020.09.02
    Firefox Java Coding Style  (0) 2020.06.13
    [Java]초기화란?  (330) 2020.05.30
    (JAVA)hasNext() vs next() 메서드 차이점?  (0) 2020.05.18

    댓글

Designed by Tistory.