Java/Basic

[Java_Basic]클래스와 인스턴스(윤성우의 열혈 Java 프로그래밍)

bangle0621 2020. 12. 26. 23:45

클래스

https://en.wikipedia.org/wiki/Wikipedia:Non-free_content_criteria#4

클래스 = 데이터 + 메소드(기능)

 

모든 프로그램은 데이터와 기능의 모임으로 이뤄져 있다.

(static 선언이 다 들어가있으면 진짜 클래스는 아니다)

class BankAaccountPo{
	static int balance = 0;	//예금 잔액
	public static void main(String[] args){
		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("잔액 :" + balance); //예금 조회를 담당하는 메소드
		return balance;
	}
}

deposit, withdraw, checkMyBalance 는 기능들이다. 

이 기능들을 묶기 위해 만들어진 것이 '클래스' BankAccountPo 이다.

 

class 라는 것은 '틀'을 꾸며놓는 것이다.

틀을 기반으로 해서 메모리에 올라갈 수 있는 사본을 만들어야 한다. 

 

이를 '인스턴스'라 표현한다.

class BankAccount{
	//인스턴스 변수
    int balance = 0;
    
    //인스턴스 메소드
    public int deposit(int amount){...}
    public int withdraw(int amount){...}
    public int checkMyBalance(){...}

new BankAccount(); //BankAccount 인스턴스 1

new BankAccount(); //BankAccount 인스턴스 2

 

인스턴스와 참조변수 

//int num 처럼 BankAccount 라는 myAcnt1 변수를 생성한다.
BankAccount myAcnt1; //참조변수 Acnt1 선언
BankAccount myAcnt2; //참조변수 Acnt2 선언


myAcnt1 = new BankAccount();		//해당 주소값을 가리키는 형태. 참조하는 형채가 된다.철수
myAcnt2 = new BankAccount();		//영희

myAcnt2.deposit(1000); 	// myAcnt1 이 참조하는 인스턴스의 deposit 메소드 호출

 

class BankAccount{
	int balance = 0;
	//예금 입금
	public int deposit(int amount){
		balance += amount;
		return balance;
	}
	//예금 출금
	public int withdraw(int amount){
		balance -= amount;
		return balance;
	}
	//예금 조회
	public int checkMyBalance(){
		System.out.println("잔액 : " + balance);
		return balance;
	}
}

class BankAcount00{
	public static void main(String[] args){
		//두개의 인스턴스 생성
		BankAccount yoon = new BankAccount();
		BankAccount park = new BankAccount();

		//각 인스턴스를 대상으로 예금을 진행
		yoon.deposit(8000);
		park.deposit(3000);

		//각 인스턴스를 대상으로 출금을 진행
		yoon.withdraw(5000);
		park.withdraw(2000);

		//각 인스턴스를 대상으로 잔액을 조회
		yoon.checkMyBalance();
		park.checkMyBalance();
	}
}

우리가 말하는 class 의 정의는 BankAccount 가 맞다 (기능들을 묶은거니까)

 

참조변수 특성

BankAccount yoon = new BankAccount();

 

yoon = new BankAccount(); 

새로운 인스턴스를 참조한다.

 

BankAccount ref1 = new BankAccount();

BankAccount ref2 = ref;

같은 인스턴스를 참조할 수 있다.

 

class BankAccount{
	int balance = 0;
	//예금 입금
	public int deposit(int amount){
		balance += amount;
		return balance;
	}
	//예금 출금
	public int withdraw(int amount){
		balance -= amount;
		return balance;
	}
	//예금 조회
	public int checkMyBalance(){
		System.out.println("잔액 : " + balance);
		return balance;
	}
}

class PassingRef{
	public static void main(String[] args){
		BankAccount ref = new BankAccount();
		ref.deposit(3000);
		ref.withdraw(300);
		check(ref);	//'참조 값' 전달
	}

	public static void check(BankAccount acc){
		acc.checkMyBalance();
	}
}

매개변수 위치에 ref 가 가지고 있는 참조값, 주소값을 전달. 해당 주소값을 acc라는 매개변수가 그 주소값을 가지게 된다.

acc가 해당 참조변수 ref 가 가리키는 인스턴스를 같이 참조하게 된다.

 

BankAccount ref = new BankAccount();

ref = null ;    //청소부

ref 가 참조하는 인스턴스와의 관계를 끊는다. 아무것도 참조하지 않도록 한다. 

 

생성자와 String 클래스

String str1 = "Happy";

str1 이라는 참조변수가 문자열 Happy 를 가리킨다.

이 문자열이 String 클래스의 인스턴스이다.

class FirstStringIntro{
	public static void main(String[] args){
		//문자열 선언과 동시에 참조변수로 참조한다.
		String str1 = "Happy";	
		String str2 = "Birthday";
		System.out.println(str1 + " " + str2);

		//메소드에 문자열을 전달하는 다양한 방법을 보여준다. 
		printString(str1);
		printString(" ");	
		printString(str2);
		printString("\n");
		printString("End of program! \n");
	}

	//String 참조변수를 매개변수로 선언하여 문자열을 전달 받을 수 있다
	public static void printString(String str){
		System.out.println(str);	
	}
}

 

클래스 정의 모델 : 인스턴스 구분에 필요한 정보

각각의 인스턴스를 구분할 수 있는 고유 정보를 멤버로 갖게 하여라!

class BankAccount{
	String accNumber;		//계좌번호
	String ssNumber;		//주민번호
	int balance = 0;		//예금 잔액

	//초기화를 위한 메소드
	public void initAccount(String acc, String ss, int bal){
		accNumber = acc;
		ssNumber = ss;
		balance = bal;
	}
	public int deposit(int amount){
		balance += amount;
		return balance;
	}
	//예금 출금
	public int withdraw(int amount){
		balance -= amount;
		return balance;
	}
	public int checkMyBalance(){
		System.out.println("계좌번호 : " + accNumber);
		System.out.println("주민번호 : " + ssNumber);
		System.out.println("예금 잔액 :" + balance + '\n');
		return balance;
	}
}

class BankAccountUnitID{
	public static void main(String[] args){
		BankAccount yoon = new BankAccount();
		yoon.initAccount("12-34-89","990990-9090990",10000);	//초기화

		BankAccount park = new BankAccount();
		park.initAccount("33-55-09","770088-5959007",10000);	//초기화

		yoon.deposit(5000);
		park.deposit(3000);
		yoon.withdraw(2000);
		park.withdraw(2000);
		yoon.checkMyBalance();
		park.checkMyBalance();
	}	
}


public void initAccount(String acc, String ss, int bal){
accNumber = acc;
ssNumber = ss;
balance = bal;
}

인스턴스 생성 직후에 초기화를 진행해야 한다. 이는 딱 한번만 진행되어야 한다.

위처럼 초기화 메소드를 따로 정의하지 않더라도 '생성자'를 정의하여도 초기화를 진행하여도 된다.

 

생성자

멤버들을 초기화 하기 위한 것. 자바에서 문법으로 정의해 놓았다.

  • 생성자도 메소드의 하나이다. 다만 그 성격이 조금 다를 뿐이다.
  • 생성자의 이름은 클래스의 이름과 동일해야 한다.
  • 생성자는 값을 반환하지 않고 반환형도 표시하지 않는다.
class BankAccount{
	String accNumber;
	String ssNumber;
	int balance;

	public BankAccount(String ass, String ss, int bal){
		accNumber = ass;
		ssNumber = ss;
		balance = bal;
	}
	public int deposit(int amount){
		balance += amount;
		return balance;
	}
	//예금 출금
	public int withdraw(int amount){
		balance -= amount;
		return balance;
	}
	public int checkMyBalance(){
		System.out.println("계좌번호 : " + accNumber);
		System.out.println("주민번호 : " + ssNumber);
		System.out.println("예금 잔액 :" + balance + '\n');
		return balance;
	}
}

class BankAccountConstructor{
	public static void main(String[] args){
		BankAccount yoon = new BankAccount("12-34-89","990990-9090990",10000);
		BankAccount park = new BankAccount("33-55-09","770088-5959007",10000);

		yoon.deposit(5000);
		park.deposit(3000);
		yoon.withdraw(2000);
		park.withdraw(2000);
		yoon.checkMyBalance();
		park.checkMyBalance();
	}
}

 

public BankAccount(String ass, String ss, int bal){
accNumber = ass;
ssNumber = ss;
balance = bal;
}

 

BankAccount yoon = new BankAccount("12-34-89","990990-9090990",10000);
BankAccount park = new BankAccount("33-55-09","770088-5959007",10000);

 

전달되는 데이처와 참조변수의 선언이 일치하여야 한다.

 

디폴트 생성자 

자바에서는 클래스 정의시에 자동으로 '디폴트 생성자'를 넣어준다.

public BankAccount(){

    //empty

}

명시적으로 이렇게라도 넣어주는게 좋다.

 

모든 클래스는 생성자를 직접 정의하는 것에 의미가 있다

 

자바의 이름 규칙

클래스의 이름 규칙

Camel Case 를 사용

클래스의 첫 문자는 대문자로 시작한다.

둘 이상의 단어가 묶여서 하나의 이름을 이룰 때, 새로 시작하는 단어는 대문자로 한다.

Circle + Point = CirclePoint

 

메소드와 변수의 이름 규칙

변형된 Camel Case  를 사용 

첫문자를 소문자로

Add + Your + Money = addYourMoney

 

상수의 이름 규칙

모든 문자를 대문자로 구성한다.

final int COLOR = 7;

final int COLOR_RAINBOW = 7;