Static
값을 공유하기 위해 static을 붙인다.
static int var; //클래스변수 : 모든 객체가 같은 값을 공유한다.
public static void main(String[] args) {
Saram s1 = new Saram();
Saram s2 = new Saram();
s1.name = "철수";
s2.name = "영희";
s1.saveMoney(100000);
s2.saveMoney(200000);
s1.saveDateMoney(300000);
s2.saveDateMoney(300000); //서로 다른 객체 간에 값을 공유하고 싶을 때
=>Class변수 dateAccount에 두 숫자가 더해진다.
System.out.println("문자열 입력>");
String str = ScanUtil.nextLine();
System.out.println(str);
System.out.println("숫자 입력>");
int num = ScanUtil.nextInt();
System.out.println(num);
}
}
class Saram{
String name;
int account;
void saveMoney(int money){
account += money;
System.out.println(name + "의 통장 잔고 : " + account);
Math.random();//클래스 메서드의 한 종류
}
static int dateAccount;
void saveDateMoney(int money){
dateAccount += money;
System.out.println("데이트 통장 잔고 : " + dateAccount);
}
}
스캐너를 그때그때 만들지 않아도 쓸 수 있는 클래스
package e_oop;
import java.util.Scanner;
public class ScanUtil {
private static Scanner s = new Scanner(System.in);
public static String nextLine(){
return s.nextLine();
}
public static int nextInt(){
return Integer.parseInt(s.nextLine());
}
}
JVM(Java Virtual Machine)
JVM 메모리 구조
프로그램 실행시 메모리 구조
//1. 프로그램 실행시 main(), classVar, classMethod가 Method Area에 저장됨
//2. main()이 호출되어 CallStack에 저장됨
System.out.println(classVar);
//3. System클래스의 out이 MethodArea에 저장됨
//4. println()이 호출되어 CallStack에 저장됨
//5. println()이 classVar를 출력 후 CallStack에서 삭제됨
classMethod();
//6. classMehod()가 호출되어 CallStack에 저장되었다가 메서드가 종료되면 삭제됨
JVM jvm = new JVM();
//7. JVM객체가 Heap에 저장됨
//8. jvm변수가 CallStack에 생성되고, JVM객체의 주소가 저장됨
System.out.println(jvm.instanceVar);
//9. println()이 호출되어 CallStack에 저장되었다가 instanceVar를 출력 후 삭제됨
jvm.instanceMethod();
//10. instanceMethod()가 호출되어 CallStack에 저장되었다가 메서드가 종료되면 삭제됨
jvm = null; //주소가 null로 바뀌어 알 수 없어짐 => GC가 삭제함
//11. jvm변수에 null이 저장됨
//12. 어디에서도 주소를 참조하지 않는 JVM객체는 GarbageCollector에 의해 삭제됨
//13. main()의 실행이 종료되어 CallStack에서 삭제됨
//14. 프로그램이 종료되고 MethodArea의 데이터가 삭제됨
초기화 방법
명시적 초기화
int var = 10;
static int classVar = 20;
초기화 블럭
(여러 줄의 초기화가 필요할 때 사용)- {}:인스턴스 변수를 초기화 / static{}:클래스 변수를 초기화
{
var = 30;
}
static{
classVar = 40;
}
생성자
Variableinit(){
var = 50;
//생성자 사용 이유
//초기화에 여러 줄의 코드가 필요할 때
//초기화에 파라미터가 필요할 때 - 외부에서 값을 설정해야 할 때
}
public static void main(String[] args) {
Init i = new Init(); //클래스 이름과 똑같은 메서드를 호출(생성자를 호출)
i.a = 10;
i.b = 20;
i.c = 30;
Init i2 = new Init();
i2.a = 40;
i2.b = 50;
i2.c = 60;
Init i3 = new Init(70, 80, 90);
}
class Init{
int a;
int b;
int c;
Init(int a, int b, int c){ //외부에서 초기화 할 값을 받아오기 위해 만든 생성자
this.a = a;
this.b = b;
this.c = c;
//this : 인스턴스 변수와 지역변수의 이름이 같을 때 둘을 구분하기 위해
전역 변수(인스턴스 변수)에 this를 붙여서 사용한다.
this=>객체의 주소가 저장되는 변수
}
//오버로딩 : 같은 이름의 메서드를 여러 개 정의하는 것(똑같은 이름을 가진 메서드가 있어도 됨. - 파라미터로 구분)
//파라미터의 갯수가 다르거나 타입이 달라야 함.
//오버로딩의 예 : system.out.println()
Init(){//파라미터가 없는 생성자
this(10, 20, 30); //생성자의 첫줄에서만 사용할 수 있다.
//this() : 생성자에서 다른 생성자를 호출할 때 사용한다.
}
}