Code Archive/JAVA

Step5. 변수의 범위, Has a 관계

쌍큐 2014. 9. 12. 13:53

- 변수의 범위 -

변수는 크게 3가지로 나누어 볼수 있다.

1. local variable

  local variable은 생성자나 메서드 내에서 사용되는 임시 변수이다.

  초기화가 필요하며, 주로 { }사이에서 생성과 소멸이 이루어진다.

  stack 영역에 저장되어 있다.

2. instance variable

 객체의 값이 저장되어 있고, 주로 class 멤버 변수이며

 객체의 소멸 주기와 함께한다. heap 영역에 저장

3. static variable

 정적 변수로 클래스 로딩시에 적재 됨, non-static에서 객체 생성이 안되면 접근 불가

 단 객체만 생성되있으면 어디서든 접근 가능

 static area(class area) 에 독립적으로 적재된다.

 *접근 방법*

  클래스명.static변수명


- Has a  관계 -

클래스 안에 멤버 변수로 클래스가 선언되있는 형태

이론적으로

 ->사람은 스마트폰을 가지고 있다. (O)

 ->스마트폰은 사람을 가지고 있다. (X)

이런 관계가 클래스 사이에서 성립해

 -> A는 B를 가지고 있다

라고 말할 수 있다.

그러므로 A클래스가 B클래스를 사용할 수 있다.

단 접근 제어자에의해 private로 선언된 것은 접근이 불가하다.



public class Car {

private String model;

private String color;

private String Test() {

return "aaa";

}

public Car(String model,String color){

this.model=model;

this.color=color;

}

public void setModel(String model){

this.model=model;

}

public String getModel(){

return model;

}

public void setColor(String color){

this.color=color;

}

public String getColor(){

return color;

}

}



public class Person {


private String name;

// Car 객체의 주소값을 담기 위해 car를 선언하고

// 참조형 데이터 타입은 클래스 명이 된다.

private Car car;

//set/get

public void setName(String name){

this.name=name;

}

public String getName(){

return name;

}

public void setCar(Car car){

this.car=car;

}

public Car getCar(){

return car;

}

}



package step5;


public class TestHasA {

public static void main(String[] args) {

// Person has a Car 관계를 표현

Person p=new Person();

p.setName("철수");

p.setCar(new Car("k5","red"));

System.out.println(p.getName());//철수

System.out.println(p.getCar());// Car 객체 주소값

System.out.println(p.getCar().getModel());// k5

System.out.println(p.getCar().getColor());// red

// 철수 객체 p 가 소유한 Car 의 모델명을 sm5 로 변경

p.getCar().setModel("sm5");

// 철수 객체 p 가 소유한 Car의 색상을 black으로 변경

p.getCar().setColor("black");

System.out.println(p.getCar().getModel());//sm5

System.out.println(p.getCar().getColor());//black

}

}