this는 인스턴스 자신을 가리키는 참조 변수로 인스턴스의 참조값이 저장되어 있다.
public class LowerClass{
int x;
int y;
public LowerClass(){
x = 20;
y = 20;
}
public LowerClass(int x){
this(); //자신의 Default constructor를 호출한다
this.x = x;
}
public LowerClass(int x, int y){
this.y = y;
//오버로딩 생성자 호출시 생성자문은 첫번째로 호출되어야 한다
this(x); //컴파일 오류 발생 - Call to 'this()' must be first statement in constructor body
}
}
Class TestA{
void method1(){
System.out.println("method1 call");
}
void method2(){
System.out.println("method2 call");
//컴파일러가 자동으로 this를 추가한다
method1(); //this.method1();
}
}
public class TestThisEx2{
public static void main(String[] args){
TestA test = new TestA();
test.mwthod2();
}
}
[결과]
method2 call
method1 call
class TestA3{
TestA3 getTestA3(){
return this;
}
void msg(){
System.out.println("TestA3 msg() 호출");
}
}
public class TestThisEx4{
public static void main(String[] args){
new TestA3().getTestA3().msg();
}
}
String name;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public static void main(String[] args){
TestThisEx5 obj = new TestThisEx5();
//setter/getter 메서드 호출
obj.setName("홍길동");
System.out.println("obj.name : "+obj.getName());
}
this는 각 인스턴스 메소드의 Stack Frame에 this라는 로컬변수로 메모리 영역에 존재한다.
static{ }으로 만들고(static 변수만 사용할 수 있음) 생성자보다 먼저 실행됨
클래스 변수에 대한 초기화에 사용
class load → static initializer 실행 → main method 실행 → 초기화 block 실행 → constructor 호출
class MyMath2{
long a, b;
long add(){
return a+b; //a, b는 인스턴스 변수
}
static long add(long a, long b){
return a+b; //a, b는 지역 변수
}
}
| 구분 | Java 7 (PermGen) | Java 8 (Metaspace) |
|---|---|---|
| Class 메타 데이터 | 저장 | 저장 |
| Method 메타 데이터 | 저장 | 저장 |
| Static Object 변수, 상수 | 저장 | Heap area로 이동 |
| 메모리 튜닝 | Heap, Perm 영역 튜닝(부족시) | Heap 튜닝, Native 영역은 OS가 동적 조정 |
| 메모리 옵션 | -XX:PermSize | |
| -XX:MaxPermSIze | -XX:MetaspaceSize | |
| -XX:MaxMetaspaceSize |
오직 하나의 company sigleton object를 client object가 사용하도록 하는 것이다.
싱글톤패턴 사용시 주의사항으로는 Thread-safe하게 개발해야 한다는 것이다.
public class Company{
private static Company instance = new Company();
private String name;
//Company 인스턴스를 얻을 수 있는 유일한 메서드
public static Company getInstance(){
return instance;
}
//생성자는 private 접근제어자로 선언하여 외부에서 객체 생섣을 차단
private Company(){}
}
class CompanySingletonTest{
public static void main(String[] args){
Company c = Company.getInstance();
}
}
import static java.lang.System.out;
import static java.lang.Math.*;
class StaticImportEx extends Object{
public static void main(String[] args){
//System.out.println(Math.random());
out.println(random());
//System.out.println("Math.PI :"+Math.PI);
out.println("Math.PI :"+PI);
}
}
인스턴스를 생성할 때 생성되고, 참조 변수가 없을 때 가비지 컬렉터에 의해 자동 제거
인스턴스 변수는 생성 시점에 각 타입의 기본값(0, null …)으로 자동 초기화된다.
public class A{
int instanceVariable; //인스턴스 변수
static void main(String[] args){
A a = new A();
int b = a.instanceVariable; //b는 참조 변수
}
}
같은 클래스의 모든 인스턴스들이 공유하는 변수(public일 경우 모든 클래스에서 접근 가능)
클래스가 로딩될 때 생성되고 프로그램이 종료될 때 소멸
public class A{
static int classVariable; //클래스 변수
static void main(String[] args){
int b = A.classVariable;
}
}
메서드 내에 선언되며, 메서드의 종료와 함께 소멸되고 사용 전에 꼭 초기화 해야 한다.
public int solution(int n){
int answer = 0; //answer은 지역 변수
return answer;
}