멤버 변수, 멤버 함수 : 클래스를 구성하는 구성요소로 클래스를 통해 객체를 생성하면 각 객체마다 멤버변수와 멤버함수들이 생성
정적 변수(static 변수) : 멤버변수와 다르게 객체를 생성하지 않아도, 아무리 많이 생성해도 한개만 존재하는 변수
정적변수의 이용 1. 모든 객체가 하나의 데이터를 공유하기위해서
2. 각각의 객체가 항상 같은 값을 가질 변수이기 때문에 각자 공간을 가질 필요는 없음
* 지역변수 : 메소드 내에서 생성하는 변수, 메소드 종료시 사라짐, 스택영역에 생성됨
Ex>
public class CircleTest {
public static void main(String[] args) {
Point p1 = new Point();
Point p2 = new Point(2,3);
Circle c1 = new Circle();
c1.setRadius(20);
// 지역변수, 타입으로는 참조변수
System.out.println(p1);
System.out.println(p2);
System.out.println(c1);
c1.setCenter(p2);
System.out.println(c1);
p2.setX(12);
p2.setY(17);
System.out.println(c1);
}
}
* 멤버변수(인스턴스변수, 필드변수) : 해당클래스가 객체화 될때마다 각 객체내에 생성됨, 클래스 내부에 정의, 해당객체가 소멸될때 같이 사라짐
Ex>
public class Circle {
private int radius;
private Point center;
// 멤버변수
public Circle() {
radius = 0;
center = new Point();
* 정적변수(클래스변수)
1. 모든객체를 통틀어서 1개만 있는 변수, 해당 클래스로 객체를 하나도 안만들었어도 1개만 존재하고 객체를 계속 만들어도 1개만존재
2. 클래스가 객채화 되는것과 상관없음
3. 클래스 내부에 static 키워드를 포함해서 정의하며 프로그램이 실행될때 생성, 프로그램이 종료될때 사라짐
4. 같은 클래스로 만든객체들은 같은 클래스 영역에 있으니까 private클래스 변수에도 자유롭게 접근 가능 → 해당 클래스로 만든 모든 객체들의 멤버함수에서 자유롭게 접근이가능 → 해당 클래스의 모든 객체들이 공유 할 수 있는공간
Ex>
public class Car {
private int speed;
private int mileage;
private String color;
private int id;
public static int numberOfCars; // 정적변수
private static final int INCREASE_AMOUNT = 10;
public static int getNumberOfCars(){
return numberOfCars;
}
public Car()
{
id = ++numberOfCars;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public int getMileage() {
return mileage;
}
public void setMileage(int mileage) {
this.mileage = mileage;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
} // 멤버함수
* 멤버함수
: 클래스 내에 정의, 해당 클래스로 객체를 생성 할 때 마다 각 객체 내에 생성됨, 해당 객체가 소멸 될 때 사라짐
* 정적함수
★★정적함수에서는 멤버변수에 접근할수 없음!!!
멤버변수의 상태와 상관없는 동작을 수행하는 기능을 구현할 때
정적변수에 대한 getter/setter를 만들거나 객체의 상태와 상관없는 동작을 수행하는 메소드를 정의할 때 사용