본문 바로가기

언어/Java

클래스, 인스턴스, 생성자

public class hello2 {
	static int balance = 0;
	
	public static void main(String[] arg) {
		deposit(10000);
		CheckMyBalance();
		withdraw(3000);
		CheckMyBalance();
	}
	
	public static int deposit(int amount) {
		balance += amount;
		return balance;
	}
	
	public static int withdraw(int amount) {
		balance -= amount;
		return balance;
	}
	
	public static int CheckMyBalance() {
		System.out.println("money: " + balance);
		return balance;
	}
	
}

 

클래스

 

= 인스턴스 변수 + 인스턴스 메소드

 

데이터 : 프로그램 상에서의 데이터

balance

메소드 : 프로그램 상에서의 기능 

deposit, withdraw, CheckMyBalance

 

 

 

인스턴스 ( 객체 )

 

= 소프트웨어에 구현된 구체적인 실체

   ★ 인스턴스 변수는 같은 클래스 내에 위치한 메소드 내에서 접근 가능하다

 

인스턴스 변수 ( 멤버 변수, 필드 ) : 클래스 내에 선언된 변수

                                                        int balance = 0;

인스턴스 메소드 : 클래스 내에 정의된 메소드

                              public static int deposit(int amount) { ... } 

                              public static int withdraw(int amount) { ... } 

                              public static int CheckMyBalance() { ... } 

 

클래스 안에 인스턴스 변수, 메소드를 사용하기 위해 클래스 인스턴스 화를 해야됨

 

new hello2();

-> hello2 클래스에 정의된 변수, 메소드를 담은 인스턴스가 생성된다 ( 실제 메모리 공간에 존재한다 )

    클래스 인스턴스 화는 여러개 시킬 수 있다

사용하기 위해 인스턴스를 참조 ( 가르키는 )하는 참조변수가 필요하다

 

 

 

참조변수

 

= 실제 값을 가진 변수가 아니라, 값이 들어가 있는 주소를 가지고 있는 변수

 

참조변수 myAcnt 선언

hello2 myAcnt;

 

참조변수 -> 인스턴스 ( 객체 ) 

hello2 myAcnt1;
hello2 myAcnt2;

myAcnt1 = new hello2();
myAcnt2 = new hello2();

hello2 myAcnt1 - 참조타입 변수명

: 참조변수

new hello2 - new 참조class명()

: 인스턴스 ( 객체, object )

즉 object를 직접 할당하는 것이 아닌 참조를 이용해 object을 활용한다

참고) [자바] Reference와 Object의 차이 (tistory.com)

 

[자바] Reference와 Object의 차이

Reference와 Object Object는 Class의 인스턴스로 특정 메모리 슬롯에 저장됩니다. Class는 Object를 어떻게 생성해야하는지 설명되어 있는 템플릿 같은 것 입니다. Reference는 'Object 변수나 함수'가 저장된

kimdabang.tistory.com

 

class hello4 {
	int balance = 0;
	
	public int deposit(int amount) {
		balance += amount;
		return balance;
	}
	
	public int withdraw(int amount) {
		balance -= amount;
		return balance;
	}
	
	public int CheckMyBalance(String name) {
		System.out.println( name +" money: " + balance);
		return balance;
	}
}

class hello3 {
	
	public static void main(String[] arg) {
		
		hello4 yoon = new hello4();
		hello4 park = new hello4();
		
		yoon.deposit(10000);
		park.deposit(70000);
		
		yoon.CheckMyBalance("yoon");
		park.CheckMyBalance("park");
		
		yoon.withdraw(100);
		park.withdraw(700);
		
		yoon.CheckMyBalance("yoon");
		park.CheckMyBalance("park");
	}

}

yoon, park 각각 다른 변수로 메모리 할당하여 hello4를 인스턴스 화 시켰다

 

생성자 ( constructor )

 

= 인스턴스가 생성될 때마다 호출되는 '인스턴스 초기화 메소드' 이다.

   생성자의 이름은 클래스의 이름과 동일해야 한다

   생성자는 값을 반환하지 않고 반환형도 표시하지 않는다

 

생성자 메소드를 사용하지 않을 때 코드

class hello6 {
	...
}

hello6 yoon = new hello6();
hello6 park = new hello6();
		
yoon.deposit(10000);
park.deposit(70000);

 

생성자 메소드를 사용할 때 코드

class hello6 {
	public hello6(int money) {
		balance = money;
	}
    
    ....
}
    
hello6 yoon = new hello6(10000);
hello6 park = new hello6(70000);

디폴트 생성자 : 인자를 전달받지 않는 형태로 정의되 삽입된다

 

생성자 추가 참조 자료) 4. Java 자바 - 클래스의 구성 멤버 [ 생성자 ] (tistory.com)

 

4. Java 자바 - 클래스의 구성 멤버 [ 생성자 ]

생성자 new 연산자와 같이 사용되어 클래스로부터 객체를 생성할 때 호출되어 객체의 초기화를 담당한다. 객체 초기화 : 필드를 초기화하거나, 메소드를 호출해서 객체를 사용할 준비를 하는 것

kephilab.tistory.com

 

'언어 > Java' 카테고리의 다른 글

static - 정적 변수, 정적 메소드  (0) 2022.06.20
정보 은닉, 접근 수준 시지자, 캡슐화  (0) 2022.06.19
클래스 패스, 패키지  (0) 2022.06.19
메소드 재귀 호출  (0) 2022.06.18
자바 컴파일 실행 원리  (0) 2022.06.13