Coding/Java
Static
코딩;
2021. 12. 17. 07:08
Main class
public class MainClass {
public static void main(String[] args) {
/*
static : 정적 <=> 동적(dynamic)
variable
method
*/
MyClass cls = new MyClass();
cls.func();
cls.func();
cls.func();
MyClass mycls = new MyClass();
mycls.func();
mycls.func();
// mycls.staticNumber= 12;
MyClass.staticNumber = 14; // 이렇게 접근해서 사용하는 경우가 많음
mycls.func();
// 메소드
YouClass yc = new YouClass();
yc.memberMethod(); // 멤버메소드, 인스턴스메소드
// ↑ 인스턴스
YouClass.staticMethod(); // static메소드, class메소드
YouClass.swap(null, 0, 0);
}
}
My class
public class MyClass {
private int number; // 멤버변수
public static int staticNumber; // 정적변수 -> 프로그램이 켜질때 먼저 영역을 잡고 프로그램이 꺼질때 꺼짐
// 객체를 10개를 만들든 100개를 만들던 static영역은 하나
// global variable(전역변수)로도 사용하는 경우가 있다.
public void method(int number) { // 매개변수 -> 외부에서 들어오는 값에따라 달라짐
int localnumber; // 지역(local)변수
{
int localnum;
}
}
public void func() {
int localnumber = 0;
localnumber++;
number++;
staticNumber++; // 멤버변수와 정적변수는 자동적으로 0으로 세팅되나 초기화 안하면 초기화 안됨
System.out.println("local변수: " + localnumber);
System.out.println("멤버변수: " + number);
System.out.println("정적변수: " + staticNumber);
YouClass.swap(null, localnumber, localnumber);
// 이렇게 자주 불러주는 함수는 static으로 설정해서
// 인스턴스를 통해 불러올 필요 없이 클래스명으로 불러와서 편하다.
}
}
You class
public class YouClass {
int number;
public void memberMethod() {
System.out.println("YouClass memberMethod()");
}
public static void staticMethod() {
System.out.println("YouClass staticMethod()");
// 멤버변수
// number = 1;
// memberMethod();
// this
// super
// 이것들은 모두 static method 안에 못씀
swap(null, 0, 0);
// 같은 클래스 내에서는 바로 불러올 수 있음 - static method
}
public static void swap(int arr[], int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
} // 객체로 만들 필요 없이 간단하게 하나의 처리만 하기에는
// static method가 매우 유용함 -> 속도가 빠르기 때문에
}