클래스 상속 연습을 위한 마이너스 통장 예제 코드
Main.java
public class Main {
public static void main(String[] args) {
Account maccount = new Account("1002-03-0001050", "김진형", "2013-01-04", 100000);
maccount.withdraw(40000); // 잔액 60,000
maccount.withdraw(40000); // 잔액 20,000
maccount.withdraw(40000); // 잔액 -20,000 (마이너스 한도 사용 및 남은 한도 10000)
maccount.withdraw(40000); // 실패 (한도 초과)
}
}
Account.java
public class Account {
String account_num;
String depositor;
String date;
int balance;
public Account(String account_num, String depositor, String date, int balance) {
this.account_num = account_num;
this.depositor = depositor;
this.date = date;
this.balance = balance;
}
public void withdraw(int amount) {
if (balance >= amount) {
balance -= amount;
System.out.println(account_num + " 출금 완료! 남은 잔액: " + balance);
} else {
System.out.println(account_num + " 출금 실패! 한도 초과. 현재 잔액: " + "-" + balance) ;
}
}
}
final이란?

변수 앞에 final이 붙으면 선언문이나 생성자 안에서 반드시 처음 값을
지정해야 하고, 그 변수의 값을 변경할 수 없습니다.
final 변수에는 새로운 값을 저장할 수 없습니다.
이때 처음 값을 설정하는 것을 ‘초기화'라고 합니다.
static이란?
static 클래스로 생성된 객체들의 변수는 모두 같은 메모리 주소에 값을 저장하므로 결과적으로는 객체들끼리 그 값을 공유할 수 있습니다.
Abstract 추상 클래스란?

예시 코드 (회사에서 사용함.)

팀장 - "추상 클래스야. 이러한 입력과 출력을 해야해"
=> 추상 클래스를 사용하여 지정해놓으면 실체를 파악할 수 있습니다.
직원 - "예 알겠습니다."
아래의 예제 코드를 확인해보세요!


=> 이처럼 직원은 이 추상적인 클래스를 상속받아서 오버라이딩을 통해 실체로 만들 수 있는 것이죠.
prog04.java
public class prog04 {
public static void main(String[] args) throws Exception {
sword s = new sword();
s.attack();
Gun g = new Gun();
g.attack();
}
}
Gun.java
public class Gun extends weapon{
public void attack(){
System.out.println("총을 쏘다.");
}
}
sword.java
public class sword extends weapon {
public void attack(){
System.out.println("칼로 찌르다.");
}
}
weapon.java
abstract class weapon {
abstract void attack();
}