static 메소드(클래스 메소드)

CODEDRAGON Development/Java

반응형

 

static

·         static 예약어

·         static정의 형식

·         http://codedragon.tistory.com/2482

·         static변수(class 변수)

·         http://codedragon.tistory.com/4606

·         static 메소드(클래스 메소드)

 

 

 

static 메소드(클래스 메소드)

·         static 메소드의 기본적인 특성과 접근방법은 static 변수와 동일

·         인스턴스를 생성하지 않아도 static 메소드는 호출 가능

public class StaticCount {

 

public static void showNumber(int number) {

System.out.println(numbert);

}

}

 

public class StaticEx01 {

 

public static void main(String[] args) {

StaticCount sc1= new StaticCount();

sc1.showNumber(20); //인스턴스 이름을 통한 접근방법

StaticCount.showNumber(30); //클래스 이름을 통한 접근방법

}

 

 

 

 

static 메소드 정의

메소드 내에서 인스턴스 변수가 포함되어 있지 않다면 static 메소드로 정의

public class StaticCount {

 

public static void showNumber(int number) {

System.out.println(number);

}

 

public static int add(int num1, int num2) {

return num1 + num2;

}

 

public static int items(int num1, int num2) {

return num1 * num2;

}

}

 

public class StaticEx01 {

 

public static void main(String[] args) {

StaticCount sc1= new StaticCount();

sc1.showNumber(20); //인스턴스 이름을 통한 접근방법

StaticCount.showNumber(30); //클래스 이름을 통한 접근방법

}

 

 

   

   

static 메소드의 인스턴스 접근은 불가능


class MyMath {

int number1;

static int number2;

 

static void plusNumber() {

number1++; // 불가능, Error, static 메소드의 인스턴스 접근은 불가능

number2++; // 가능

}

}

 

MyMath myMath1 = new MyMath(); // 인스턴스 생성

MyMath myMath2 = new MyMath();

MyMath myMath3 = new MyMath();

 

  

 

반응형