[Java] 클래스와 객체 2

C____JIN·2022년 6월 16일
0
post-thumbnail

this 예약어

this 예약어란?

  • 생성된 인스턴스 스스로를 가리키는 예약어
class BirthDay {
	int day;
    int month;
    int year;
    
    public void setYear(int year) {
        this.year = year;
    }
    
    public void printThis() {
    	System.out.println(this);
    }
}

public class Example {
	public static void main(String[] args) {
    	BirthDay bDay = new BirthDay();
        bDay.setYear(2000);
        System.out.println(bDay);
        bDay.printThis();
    }
}

  • thisdDay 클래스는 모두 생성된 BirthDay 클래스를 가르킴

생성자에서 다른 생성자를 호출하는 this

Person() {
	this("이름 없음", 1);
}

Person(String name, int age) {
	this.name = name;
    this.age = age;
}
  • this를 사용해 Person(String, int) 생성자 호출

자신의 주소를 반환하는 this

Person returnItSelf() {
	return this;
}
  • this를 사용하면 자신의 주소 값을 반환할 수 있음

static 변수

static 변수란?

  • 정적 변수
  • 프로그램이 실행되어 메모리에 올라갔을 때 딱 한 번 메모리 공간 할당
    • 그 값은 모든 인스턴스가 공유

사용

public class Student {
	public static int serialNum = 1000;
    public int sutdentId;
    public String studentName;
    public int grade;
    public String address;
    
    public String getStudentName() {
    	return studentName;
    }
    
    public void setStudentname(String name) {
    	studentName = name;
    }
}
public class Test {
	public static void main(String[] args) {
        Student student1 = new Student();
        student1.setStudentName("cheoljin");
        System.out.println(student1.serialNum); // 1000
        student1.serialNum++;
    
        Student student2 = new Student();
        student2.setStudentName("cheoljinpark");
        System.out.println(student2.serialNum); //1001
        System.out.println(student1.serialNum); //1001
 	}
}

  • student1과 student2는 static으로 선언된 변수 serialNum을 공유함

변수 유효 범위

변수 유형선언 위치사용 범위메모리생성과 소멸
지역 변수
(로컬 변수)
함수 내부에 선언함수 내부에서만 사용스택함수가 호출될 때 생성되고
함수가 끝나면 소멸함

멤버 변수

(인스턴스 변수)

클래스 멤버 변수로 선언클래스 내부에서 사용하고
private이 아니면
참조 변수로
다른 클래스에서 사용 가능
인스턴스가 생성될 때 힙에 생성되고,
가비지 컬렉터가 메모리를
수거할 때 소멸됨

static 변수

(클래스 변수)

static 예약어를 사용하여
클래스 내부에 선언
클래스 내부에서 사용하고
private이 아니면
클래스 이름으로
다른 클래스에서 사용 가능
데이터 영역프로그램이 처음 시작할 때
상수와 함께 데이터 영역에 생성되고
프로그램이 끝나고
메모리를 해제할 때 소멸됨

싱글톤 패턴

싱글톤 패턴이란?

  • 인스턴스를 단 하나만 생성하는 디자인 패턴

싱글톤 패턴 구현하기

  1. private 생성자 만들기
public class Company {
	private Company() {}
}
  1. 클래스 내부에 static으로 유일한 인스턴스 생성하기
public static Company {
	private static Company instance = new Company(); // 유일한 인스턴스
    private Company() {}
}
  1. 외부에서 참조할 수 있는 public 메서드 만들기
public static Company {
	private static Company instance = new Company(); // 유일한 인스턴스
    private Company() {}
    
    public static Company get Instance() {
    	if(instance == null) {
        	instance = new Company(); // 인스턴스가 없으면 생성
        }
        return instance; // 유일하게 생성한 인스턴스 반환
    }
}
  1. 실제로 사용하는 코드 만들기
public class CompanyTest {
	public static void main(String[] args) {
    	Company myCompany1 = Company.getInstance();
        Company myCompany2 = Company.getInstance();
        System.out.println(myCompany1 == myCompany2); // 두 변수가 같은 주소인지 확인
        //true
    }
}
profile
개발 블로그🌐 개발일지💻

0개의 댓글