return + 값 : 메소드를 호출한 영역으로 값을 반환
return만 (값 ×) : 메소드의 종료
붕어빵 틀 = 클래스 (컴파일.class)
붕어빵 = 객체 (클래스를 메모리에 올리기 위한 것)
클래스(class) = '객체를 정의하는 틀 또는 설계도'
➡ 객체의 상태를 나타내는 필드(field)와 객체의 행동을 나타내는 메소드(method)로 구성됨.
필드란...
✔클래스 변수
✔클래스 메소드
static int add(int x, int y) { return x + y; } // 클래스 메소드
public class Member02 {
public static void main(String[] args) {
System.out.println(Method.add(20, 30)); // 클래스 메소드의 호출
Method myMethod = new Method(); // 인스턴스 생성
System.out.println(myMethod.add()); // 인스턴스 메소드의 호출
}
}
예제처럼 클래스 메소드는 인스턴스 변수를 사용하지 않고, 전달된 매개변수만으로 동작하는 메소드이다.
클래스의 "인스턴스화" = 클래스로부터 객체(object)를 선언하는 과정
➡ 클래스를 사용하기 위해서는 우선 해당 클래스 타입의 객체(object)를 선언해야 됨.
➡ 선언된 해당 클래스 타입의 객체를 인스턴스라고 한다.
✔인스턴스 변수
✔인스턴스 메소드
class Car {
boolean door; // 인스턴스 변수
void openDoor() { // 인스턴스 메소드
door = true;
}
static void toggleDoor(boolean d) { // 클래스 메소드
return !d;
}
}
public class BankAccount {
static int balance = 0; // 예금 잔액
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;
}
public static void main(String[] args) {
deposit(10000);
checkMyBalance();
withdraw(3000);
checkMyBalance();
}
}
[결과]
잔액 : 10000
잔액 : 7000
BankAccount 폴더 안에 (클래스)BankAccount.java, (클래스)BankAccountTest.java 만들고 작성한다.
public class BankAccount {
static int balance = 0; // 예금 잔액
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;
}
}
public class BankAccountTest {
public static void main(String[] args) {
BankAccount yoon; // 변수 선언 (데이터 타입 + 변수명)
yoon = new BankAccount(); // 객체 생성
yoon.deposit(5000);
yoon.checkMyBalance();
yoon.withdraw(1000);
yoon.checkMyBalance();
}
}
[결과]
잔액 : 5000
잔액 : 4000