Backend/JAVA2 멘토시리즈

JAVA Eclipse 21 인스턴스 변수와 클래스 변수

쏠솔랄라 2023. 5. 7. 11:06

 

 

인스턴스 변수

 

: 객체마다 갖는 고유한 변수

 

인스턴스를 생성할 때 만들어지며, 각각의 인스턴스마다 자신의 값을 가지고 있다

각 인스턴스마다 다른 값을 가져야 할 때 생성

인스턴스 생성 시(new 클래스명();) 메모리에 생성

 

class 클래스명{
     자료형 변수명;
}

* 기존방식과 동일

 

 

클래스 변수

 

: 모든 객체가 동일한 값을 갖는 변수

 

모든 인스턴스가 같은 저장공간을 공유

클래스가 처음 메모리에 로딩될 때 생성

인스턴스 없이 사용 가능

 

class 클래스명 {
     static 자료형 변수명;
}

* 변수 선언 시 자료형 앞에 static키워드를 붙인다

 

 


 

 

ex1.

회원정보를 저장하는 Member클래스를 생성

 

centerName의 값을 static으로 지정해 주면, 이 값은 인스턴스 변수가 아닌 클래스 변수가 된다

 

 

main 클래스에서 각 회원의 정보를 저장한 후 출력

 

 

이후 member1의 centerName을 변경 후 출력

 

member1의 값만 변경했는데도 나머지 3명 회원 정보도 변경됨

 

=> 클래스변수는 모든 인스턴스가 같은 주소를 저장하고 있기 때문에

각각의 이름을 바꾸지 않고 하나의 변수만 변경해도 모든 값이 변한다

 

 

ex2.

 

1) 자동차 정보를 저장하는 CarPractice 클래스 생성

2) main 클래스에 mycar1과 mycar2의 두 개의 정보 생성

3) mycar2의 speed와 wheel값을 변경

 

 

출력화면

 

 

speed값은 mycar2에만 영향을 미치나

wheel 값은 mycar1과 mycar2에 모두 영향을 미친다

 

=> speed 값은 인스턴스 변수로 객체마다 각각의 고유한 값을 유지하고 있으며

wheel 값은 클래스 변수여서 모든 객체가 공통적으로 가지고 있는 공유하는 변수이기 때문

 

 


 


JAVA Eclipse 01 프로그램, 프로그래밍, 기계어, JAVA
https://developernew.tistory.com/63

JAVA Eclipse 02 자바 출력메서드와 입력메서드
https://developernew.tistory.com/71

JAVA Eclipse 03 변수, 자료형, 형변환, 변수의 상수화
https://developernew.tistory.com/74

JAVA Eclipse 04 연산자 정의, 연산자 종류, 연산자 우선순위
https://developernew.tistory.com/78

JAVA Eclipse 05 논리연산자, 비트연산자
https://developernew.tistory.com/80

JAVA Eclipse 06 기타연산자 - 삼항연산자, 대입연산자, 복합대입연산자, instanceof
https://developernew.tistory.com/84

JAVA Eclipse 07 제어문 : 조건문
https://developernew.tistory.com/88

JAVA Eclipse 08 제어문 : 조건문 switch + Random 클래스
https://developernew.tistory.com/93

JAVA Eclipse 09 제어문 : 반복문 for
https://developernew.tistory.com/102

JAVA Eclipse 10 제어문 : 반복문 while, do-while
https://developernew.tistory.com/103

JAVA Eclipse 11 제어문 : 반복문의 break, continue
https://developernew.tistory.com/106

JAVA Eclipse 12 배열 : 배열의 개념 및 사용
https://developernew.tistory.com/107

JAVA Eclipse 13 배열 : 예제풀이, 로또번호 생성기
https://developernew.tistory.com/115

JAVA Eclipse 14 배열 : 다차원배열
https://developernew.tistory.com/117

JAVA Eclipse 15 배열의 복제, for ~ each문
https://developernew.tistory.com/120

JAVA Eclipse 16 카페 주문 시스템(키오스크) 배열과 제어문(반복문, 조건문)으로 풀기
https://developernew.tistory.com/124

JAVA Eclipse 17 method 메서드(메소드)
https://developernew.tistory.com/126

JAVA Eclipse 18 메서드(메소드) 오버로딩
https://developernew.tistory.com/133

JAVA Eclipse 19 객체지향 언어
https://developernew.tistory.com/135

JAVA Eclipse 20 클래스와 객체

https://developernew.tistory.com/155