* static 변수(정적 변수, 클래스 변수)
- static 변수는 JVM으로 소스 로딩시에 메모리 할당을 받음으로 new 명령어보다
먼저 실행되며 메모리에 오로지 하나만 생성됨으로 클래스 변수라고 한다.
- 객체 생성과 관련이 없음으로 '클래스명.변수명', '클래스명.메소드명'으로 접근한다.
객체명으로 접근시 권장아님으로 경고 발생.
- static변수는 초기값으로 0으로 할당된다
- static변수는 프로그램을 실행시 최초 한번만 특정값으로 초기화되고
더이상 초기화가 되지않는다.(메모리할당을 단1회만 한다)
- static 변수는 객체를 여러번 생성해도 한번만 생성이 된다.
- static 변수는 객체를 만들기 전에 초기화가 됨으로 멤버 메소드안에 선언 할 수 없다.
- static 변수는 최초 사용 요청시 한번만 메모리 할당(#100번지)을 받고
모든 객체가 이 메모리를 공유한다.
그러나 인스턴스 변수는 객체 생성시마다 메모리를 새롭게 할당 받는다.
- 기본적으로 모든 클래스의 사용은 new를 이용하여 메모리 할당한 후 가능하지만
static 변수와 메소드는 new를 이용해 객체를 만들지 않고 사용 가능하다
- 프로그램내에서 값이 변하지 않는 상수나, 모든 객체가 공유하는 변수의
값을 유지할 때 사용한다.
- 자주 생성이 필요한 문자열은 static 변수를 이용하면 1회만 생성되어 처리 속도를
많이 향상 시킬 수 있다.
- 자주 생성이 필요한 객체의 경우 static 객체 형식으로 생성하면 객체가 하나만
메모리에 생성됨으로 처리 속도를 많이 향상 시킬 수 있다.
- 하나의 클래스로 여러 개의 객체가 생성될때 단 하나만 생성되며 모든 객체들이 공유하는 개념.
- 객체가 생성되지 않아도 이미 존재하고 있으므로 객체를 생성하지 않아도 접근할 수 있다.
- 특정객체에서 값을 수정하게 되면 다른 모든 객체들이 수정된 값을 사용하게 된다.
- 같은 프로그램내의 어디서나 접근할 수 있는 전역변수의 성격을 갖음.
파일명 : StaticEx1.java
package oop3;
class Account
{
String name;
String sabun; //사원번호
int pay;
static int bonus=123; //static변수
static String companyName="SAMSUNG Corp";
public Account(){}
public Account(String name,int pay)
{
this.name=name;
this.pay=pay+10;
this.bonus++;
}
void prn()
{
//static int hap;//에러
}
}
//===================
public class staticEx1 {
public static void main(String[] args) {
/*
Account acc=new Account();
acc.name="kim";
acc.sabun="b004";
acc.pay=5000;
//static변수는 객체를 선언한 후 사용하는 방법은 비추천한다
//acc.bonus=100;//비추천
System.out.println(acc.pay);
System.out.println(acc.bonus);//비추천
//static변수는 클래스명으로 직접 접근해서 사용한다. 추천
System.out.println(Account.bonus);//추천
Account two=new Account();
two.pay=3000;
System.out.println(two.pay);
two.bonus=123;
System.out.println(two.bonus);//123
System.out.println(acc.bonus);//123
System.out.println(Account.bonus);//123
acc.bonus=456;//#100번지값을 다시 대입
System.out.println(acc.bonus);
System.out.println(two.bonus);
System.out.println(Account.bonus);
acc.prn();
two.prn();
*/
Account three=new Account("kim",1000);//1010 bonus=124
Account four=new Account("lee",1000);//1010 bonus=125
System.out.println(three.pay);
System.out.println(four.pay);
System.out.println(Account.bonus); //125
Account.bonus=Account.bonus+1;//125+1
System.out.println(three.bonus); //126 사용형식 비추천
}
}
파일명 : StaticEx2.java
package oop3;
//객체를 3개만 생성되도록 제한을 둔 경우
class DataObj{
String name = "대한민국";
static int count = 0; // 한번만 메모리 할당(초기화)발생
// int count = 0; // 객체 생성시마다 새로운 초기화 발생
public DataObj(){
count++;
System.out.println("객체 생성 완료" + count);
}
}
public class StaticEx2 {
public static void main(String[] args) {
/*
while(true)
{
DataObj obj=new DataObj(); //count=1 count=2
if (DataObj.count==3) break;
}
*/
System.out.println(Double.SIZE);
}
}
* static 메소드 (클래스 메소드)
- 단순한 값의 변화 구현시에 사용한다. wrapper클래스 참고
- int pay = Integer.parseInt("123");
- 공유차원에서 사용
- 객체 생성없이 클래스이름.메소드이름() 으로 바로 접근해서 호출 가능
- static 메소드 안에서 instance 변수(멤버변수)들을 참조할 수 없다.
- static메소드는 인스턴스메소드를 호출할 수 없음.
파일명 : StaticEx3.java
package oop3;
//static 메소드
class Animal
{
String name;
int age;
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
}
//=========================
class Fruit
{
String name;
int price;
public Fruit(String name, int price) {
this.name = name;
this.price = price;
}
}
//========================
class Print
{
int a;
static void prn1(Animal dog)
{
//a=10;//에러
//hap();//에러
System.out.println(dog.name+dog.age);
}
static void prn2(Fruit apple)
{
System.out.println(apple.name+apple.price);
}
void hap()
{
}
}
//=======================
public class StaticEx3 {
public static void main(String[] args) {
Animal dog=new Animal("PUPPY",5);
Fruit apple=new Fruit("대구사과",1000);
Print.prn1(dog);
Print.prn2(apple);
}
}
* static 초기화 (static initializers)
static {
// 수행문;
}
- 클래스 내부에서 꼭 필요한 static변수(클래스변수)들의
초기화를 미리 정의하는 용도로 많이 사용
- 클래스가 메모리에 처음 로딩될 때 한번만 수행됨.
파일명 : StaticEx4.java
package oop3;
//static 초기화 블럭예제
class Test
{
static String companyName;
static int password;
static
{
companyName="SAMSUNG Corp";
password=1004;
//int a;비추천
}
}
public class StaticEx4 {
public static void main(String[] args) {
System.out.println(Test.companyName);
System.out.println(Test.password);
//System.out.println(Test.a); //에러
System.out.println(Math.E);
System.out.println(Math.PI);
/*
* class Math{
* static double E=2.7182~~~~;
* static double PI=3.14~~~;
* }
*
* */
}
}
'..열심히 공부하세.. > JAVA 문법' 카테고리의 다른 글
| [23] 접근제어자 (0) | 2012.05.01 |
|---|---|
| [22] final 키워드 (0) | 2012.04.27 |
| [20] this, this() (0) | 2012.04.26 |
| [19] 변수의 유효범위 (Scope) (0) | 2012.04.26 |
| [18] 생성자 함수 (0) | 2012.04.26 |