BackEnd/JAVA

JAVA 접근제어자 개념 정리, Static

H_Develop 2022. 7. 29. 16:28

// public : can be accessed from all, 
// protected : only be accessed within the same packages inherited object
// default : only be accessed within the same packages, possibly omitted
// private : only be accessed within present object

// 보통 class : public, default (default 생략가능)를 사용
// in constructor and member method and member variable : public, protected, default, private 를 많이 사용한다.

 

 

 

Static
정적 static은 고정된 이란 의미를 가지고 있다.
static 변수와 static 메서드를 만들 수 있는데,
다른 말로 정적 필드와 정적 메서드라 하며, 둘을 합쳐 정적 맴버라고 한다(클래스 맴버라고도 한다).
정적 맴버와 정적 메서드는 객체(인스턴스)에 소속된 맴버가 아니라,
클래스에 고정된 맴버이기 때문에 클래스를 로딩해서 메서드 메모리 영역에 적재할 때, 클래스별로 관리된다.
따라서 클래스의 로딩이 끝나는 즉지 바로 사용 가능하다.

맴버 변수, 맴버 메서드를 선언할 때, 인스턴스로 객체를 생성해서 어디서나 공용으로 사용할 것인지,
혹은 해당 클래스에서만 사용할 것인지를 판단해서 지정하는데,
해당 클래스에서만 사용한다면 static을 붙인 변수와 메서드로 해주면 된다.

 

class Number {
	static int num = 0;	// class_member
	int num2 = 0;	// instance_member
}
class Name {
	static void print() {	// class_member_method
		System.out.println("My name is Paul");
	}
	void print2() {			// instance_member_method
		System.out.println("My name is Mary");
	}
}
public class ex2 {
	public static void main(String[] args) {
		Number number1 = new Number();
		Number number2 = new Number();
		
		number1.num++;
		number2.num2++;
		System.out.println("number1.num : " + number1.num);
		System.out.println("number1.num2 : " + number1.num2);
		System.out.println("number2.num : " + number2.num);
		System.out.println("number2.num2 : " + number2.num2);
		System.out.println();
		
		Name.print();	// without making instance, calling method
//		Name.print2();	// Error !! static method가 아님.
		Name n = new Name();
		n.print2();
	}
}

number1.num : 1
number1.num2 : 0
number2.num : 1
number2.num2 : 1

My name is Paul
My name is Mary