본문 바로가기

Programming/국비학원

220503 - 6장 클래스 확인문제, 상속(extends), 오버라이딩(재정의)

6장 클래스 확인문제
  • 객체, 클래스 개념

하나의 클래스로 여러 객체 생성 가능 (하나의 객체만 가능 => 싱글톤)

클래스 => 생성자, 메소드, 필드 필수( 생략 시 디폴트 생성)

필드 => 통상적으로 생성자 선언 전에 선언 (필수X)
필드 => 생략 시 기본값으로 자동 초기화됨
객체 생성=> 생성자 호출 필수
생성자=>다른 생성자 호출 위해 this() 사용 가능
메소드 오버로딩 : 동일 이름 메소드 여러 개 선언 => 매개변수의 타입, 수, 순서 다르게 해야 함

정적 필드,메소드 => 객체 생성 없이, 클래스 통해 접근 가능
인스턴스 필드, 메소드 => 객체 생성 필수

패키지 선언 필수 (ex. package ~;)

 

 

  • 문제 15

1. boolean login 메소드 (매개값 String id, String password) => "hong", "12345"일 경우에만 true 리턴

2. void logout 메소드 (매개값 String id) => "로그아웃되었습니다" 출력

 

=>

 

1
2
3
4
5
6
7
8
9
10
11
12
13
public class MemberService {
        boolean login(String id, String password) {
            if (id.equals("hong") && password.equals("12345")) {
                return true;
            }else {return false;}
        }
        
        void logout(String id) {
            if (id.equals("hong")) {
            System.out.println("로그아웃되었습니다.");
            }
        }
}
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class MemberEx1 {
 
    public static void main(String[] args) {
        MemberService memberService = new MemberService();
        
        boolean result = memberService.login("hong""12345");
        
        if (result) {    //true
            System.out.println("로그인되었습니다");
            memberService.logout("hong");
        }else {    //false
            System.out.println("로그인을 할 수 없습니다.");
        }
    }
}
cs

 

 

  • 문제16

println 메소드 선언 (매개값: int, boolean, double, String)

 

=>

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Printer {
    //메서드
    void println(int value) {
        System.out.println(value);
    }
    
    void println(boolean value) {    //메소드 오버로딩
        System.out.println(value);
    }
    
    void println(double value) {
        System.out.println(value);
    }
    
    void println(String value) {        
        System.out.println(value);
    }
}
cs

 

1
2
3
4
5
6
7
8
9
10
11
public class PrinterExample {
 
    public static void main(String[] args) {
        Printer printer = new Printer();
        
        printer.println(10);    //printer 객체 생성 통한 메소드 구현
        printer.println(true);
        printer.println(4.6);
        printer.println("홍길동");
    }
}
cs

 

 

  • 문제17

객체 생성 없이 println 메소드 호출

 

=> 정적 메소드 선언

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Printer {
    //정적 메소드
    static void println(int value) {
        System.out.println(value);
    }
    
    static void println(boolean value) {
        System.out.println(value);
    }
    
    static void println(double value) {
        System.out.println(value);
    }
    
    static void println(String value) {        
        System.out.println(value);
    }
}
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class PrinterExample {
 
    public static void main(String[] args) {
//        Printer printer = new Printer();
        
//        printer.println(10);    //printer 객체 생성 통한 메소드 구현
//        printer.println(true);
//        printer.println(4.6);
//        printer.println("홍길동");
        
        Printer.println(10);    //static => 객체 생성 없이 클래스 통해 바로 메소드 구현
        Printer.println(true);
        Printer.println(4.6);
        Printer.println("홍길동");
    }
}
cs

 

 

  • 문제18

싱글톤 구현

 

=>

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class ShopService {
    
    //필드
    private static ShopService service = new ShopService();  
    //service라는 이름의 ShopService 타입 객체 생성
    
    //생성자
    private ShopService(){
    }
    
    //메소드
    static ShopService getInstance() { //외부에서 이용 가능, 클래스로 메소드 구현(static)
        return service;
    }
}
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class ShopServiceEx {
 
    public static void main(String[] args) {
        ShopService obj1 = ShopService.getInstance();    
        //private 필드, 생성자->getInstance 메소드 사용
        ShopService obj2 = ShopService.getInstance();
        
        if (obj1==obj2) {
            System.out.println("같은 ShopService 객체입니다");
        }else {
            System.out.println("다른 ShopService 객쳋입니다");
        }
    }
}
cs

//
같은 ShopService 객체입니다 => 싱글톤 객체 하나

 

 

  • 문제19

외부에서 Accouont 객체의 balance 필드 변경 금지, 0<=balance<=1,000,000

1. setter, getter 이용

2. 0과 1,000,000 => MIN_BALANCE, MAX_BALANCE 상수 선언해 이용

3. setter의 매개값 음수이거나 백만원 초과 => 현재 balance값 유지

 

=>

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Account {
    //인스턴스 필드
    private int balance;
    
    //상수
    final static int MIN_BALANCE = 0;
    final static int MAX_BALANCE = 1000000;
    
    //getter (값 보여줌)
    public int getBalance() {
        return balance;
    }
    
    //setter (값 세팅)
    public void setBalance(int balance) {
        if (balance>=MIN_BALANCE && balance<=MAX_BALANCE) {
            this.balance = balance;
        }
    }
}
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class AccountEx {
 
    public static void main(String[] args) {
        Account account = new Account();
 
        account.setBalance(10000);
        System.out.println("현재 잔고 : "+account.getBalance());
        
        account.setBalance(-100);
        System.out.println("현재 잔고 : "+account.getBalance());
        
        account.setBalance(2000000);
        System.out.println("현재 잔고 : "+account.getBalance());
        
        account.setBalance(300000);
        System.out.println("현재 잔고 : "+account.getBalance());
        
    }
}
cs

//
현재 잔고 : 10000
현재 잔고 : 10000
현재 잔고 : 10000
현재 잔고 : 300000

 

 

  • 문제20

계좌관리 프로그램

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class Account {
    private String ano;
    private String owner;
    private int balance;
    
    public Account(String ano, String owner, int balance) {
        this.ano=ano;
        this.owner=owner;
        this.balance=balance;
    }
    
    public String getAno() {
        return ano;
    }
    public void setAno(String ano) {
        this.ano=ano;
    }
    
    public String getOwner() {
        return owner;
    }
    public void setOwner(String owner) {
        this.owner=owner;
    }
 
    public int getBalance() {
        return balance;
    }
    public void setBalance(int balance) {
        this.balance = balance;
    }
    
}
cs

 

 

=>

 

1. Count 사용

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import java.util.Scanner;
 
public class BankApplication {
    
    private static Account[] accountArray = new Account[100];
    private static Scanner scanner = new Scanner(System.in);
    
    static int count=0;
    
    public static void main(String[] args) {
        boolean run = true;
        while (run) {
            System.out.println("----------------------------------");
            System.out.println("1.계좌생성 2.계좌목록 3.예금 4.출금 5.종료");
            System.out.println("----------------------------------");
            System.out.print("선택>> ");
            
            int selectNo = scanner.nextInt();
            
            switch(selectNo) {
                case 1
                    createAccount();
                    break;
                case 2:
                    accountList();
                    break;
                case 3:
                    deposit();
                    break;
                case 4:
                    withdraw();
                    break;
                case 5:
                    run = false;
                    break;
            }
        }//while
        System.out.println("프로그램 종료");
    }//main
    
    //계좌 생성 메소드
    private static void createAccount() {
        System.out.println("---------------");
        System.out.println("    계좌생성     ");
        System.out.println("---------------");
        System.out.print("계좌번호 : ");
        String ano = scanner.next();
        System.out.print("\n계좌주 : ");
        String owner = scanner.next();    //.next : String 받음
        System.out.print("\n초기입금액 : ");
        int balance = scanner.nextInt();
        accountArray[count]=new Account(ano, owner, balance);   
        count++;  
        System.out.println("결과 : 계좌가 생성되었습니다.");
    }
    
    //계좌 목록 보기 메소드
    private static void accountList() {
        System.out.println("---------------");
        System.out.println("    계좌목록     ");
        System.out.println("---------------");
        for (int i=0;i<count;i++) {
            System.out.print(accountArray[i].getAno() +" ");
            System.out.print(accountArray[i].getOwner()+" ");
            System.out.println(accountArray[i].getBalance());
        }
    }
    
    //예금 메소드
    private static void deposit() {
        System.out.println("---------------");
        System.out.println("      예금     ");
        System.out.println("---------------");
        System.out.print("계좌번호 : ");
        String ano = scanner.next();
        System.out.print("\n예금액 : ");
        int amount =scanner.nextInt();
        Account account = findAccount(ano);  
        if (account==null) {    
            System.out.println("결과 : 계좌가 없습니다.");
            }else {
                account.setBalance(account.getBalance()+ amount);  
                System.out.println("결과 : 예금 성공했습니다.");
            }
    }
    
    //출금 메소드
    private static void withdraw() {
        System.out.println("---------------");
        System.out.println("      출금     ");
        System.out.println("---------------");
        System.out.print("계좌번호 : ");
        String ano = scanner.next();
        System.out.print("\n출금액 : ");
        int amount = scanner.nextInt();
        Account account = findAccount(ano);    
        if (account == null) {    
            System.out.println("결과 : 계좌가 없습니다.");
            }else {
                if (account.getBalance()<amount) {
                    System.out.println("잔액 부족");
                } else {
                account.setBalance(account.getBalance()-amount);    
                System.out.println("결과 : 출금 성공했습니다.");
                }
            }
    }
    
    //Account 배열에서 ano와 동일한 Account 객체 찾기
    private static Account findAccount(String ano) {
        Account account =null;   
        for (int i=0;i<count;i++) {
            if (accountArray[i].getAno().equals(ano)) {   
                account = accountArray[i];
                break;
            } 
        }
        return account;
    }
}
cs

 

 

2. accountArray[i]로만 전개 (더 길어짐)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import java.util.Scanner;
 
public class BankApplication2 {
    
    private static Account[] accountArray = new Account[100];    ////null 값으로 채움
    private static Scanner scanner = new Scanner(System.in);
    
//    static int count=0;
    
    public static void main(String[] args) {
        boolean run = true;
        while (run) {
            System.out.println("----------------------------------");
            System.out.println("1.계좌생성 2.계좌목록 3.예금 4.출금 5.종료");
            System.out.println("----------------------------------");
            System.out.print("선택>> ");
            
            int selectNo = scanner.nextInt();
            
            switch(selectNo) {
                case 1
                    createAccount();
                    break;
                case 2:
                    accountList();
                    break;
                case 3:
                    deposit();
                    break;
                case 4:
                    withdraw();
                    break;
                case 5:
                    run = false;
                    break;
            }
        }//while
        System.out.println("프로그램 종료");
    }//main
    
    //계좌 생성 메소드
    private static void createAccount() {
        System.out.println("---------------");
        System.out.println("    계좌생성     ");
        System.out.println("---------------");
        System.out.print("계좌번호 : ");
        String ano = scanner.next();
        System.out.print("\n계좌주 : ");
        String owner = scanner.next();    //.next : String 받음
        System.out.print("\n초기입금액 : ");
        int balance = scanner.nextInt();
        for (int i=0;i<accountArray.length;i++) {
            if (accountArray[i]==null) {
                accountArray[i]=new Account(ano, owner, balance);
                break;
            }
        }
//        count++;     ////
        System.out.println("결과 : 계좌가 생성되었습니다.");
    }
    
    //계좌 목록 보기 메소드
    private static void accountList() {
        System.out.println("---------------");
        System.out.println("    계좌목록     ");
        System.out.println("---------------");
        for (int i=0;i<accountArray.length;i++) {
            if (accountArray[i]!= null) {   
            System.out.print(accountArray[i].getAno() +" ");
            System.out.print(accountArray[i].getOwner()+" ");
            System.out.println(accountArray[i].getBalance());
            } else {break;}  
        }
    }
    
    //예금 메소드
    private static void deposit() {
        System.out.println("---------------");
        System.out.println("      예금     ");
        System.out.println("---------------");
        System.out.print("계좌번호 : ");
        String ano = scanner.next();
        System.out.print("\n예금액 : ");
        int amount =scanner.nextInt();
        Account account = findAccount(ano);    
        if (account==null) {    
            System.out.println("결과 : 계좌가 없습니다.");
            }else {
                account.setBalance(account.getBalance()+ amount);  
                System.out.println("결과 : 예금 성공했습니다.");
            }
    }
    
    //출금 메소드
    private static void withdraw() {
        System.out.println("---------------");
        System.out.println("      출금     ");
        System.out.println("---------------");
        System.out.print("계좌번호 : ");
        String ano = scanner.next();
        System.out.print("\n출금액 : ");
        int amount = scanner.nextInt();
        Account account = findAccount(ano);    
        if (account == null) {    
            System.out.println("결과 : 계좌가 없습니다.");
            }else {
                if (account.getBalance()<amount) {
                    System.out.println("잔액 부족");
                } else {
                account.setBalance(account.getBalance()-amount);    
                System.out.println("결과 : 출금 성공했습니다.");
                }
            }
    }
    
    //Account 배열에서 ano와 동일한 Account 객체 찾기
    private static Account findAccount(String ano) {
        Account account =null;    
        for (int i=0;i<accountArray.length;i++) {
            if (accountArray[i] != null){
                if (accountArray[i].getAno().equals(ano)) {    
                    account = accountArray[i];
                    break;
                } 
            }else {break;}
        }
        return account;
    }
}
cs

 

 

 

 

 

 

 

상속

다른 클래스에 필드, 메소드 물려주는 것

 

 

  • checkingaccount (Account 상속)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class Account {
 
    static final String BANKNAME = "신한은행";
    String accountNo;    
    String ownerName;  
    int balance;
 
    public Account(String accountNo, String ownerName, int balance) {
        this.accountNo=accountNo;   
        this.ownerName=ownerName;
        this.balance=balance;
    }
    
    public Account() {
    }
    
    void deposit (int amount) {  
        balance+=amount;
    }    
 
    int withdraw(int amount) throws Exception {  
        if (balance<amount) {
            throw new Exception("잔액 부족");
        } 
        balance-=amount;
        return amount;
    }    
}
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//체크카드 클래스 => 통장 있어야 체크카드 제작 가능
public class CheckingAccount extends Account {   
    //필드 추가
    String cardNo;
    
    //생성자
    public CheckingAccount(String accountNo, String ownerName, int balance, String cardNo) {
        super(accountNo, ownerName, balance);    //부모 생성자 호출
//        this.accountNo=accountNo;
//        this.ownerName=ownerName;
//        this.balance=balance;
        this.cardNo=cardNo;
    }
    
    //체크카드 지불 메소드
    int pay(String cardNo, int amount) throws Exception {
        if (!this.cardNo.equals(cardNo)) {
            throw new Exception("카드번호가 일치하지 않습니다.");
        }else {
            return withdraw(amount);
        }
    }
}
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class CheckingAccountEx1 {
 
    public static void main(String[] args) {
        CheckingAccount chulsu = new CheckingAccount("22-333""김철수"1000"1111-2222-3333");
        //Account 메소드들 상속받은 CheckingAccount
        chulsu.deposit(30000);
        try {
            int paidAmount = chulsu.pay("1111-2222-3333"11000);
            System.out.println("지불액 : "+paidAmount);
            System.out.println("잔액 : "+chulsu.balance);
        }catch(Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
cs

//
지불액 : 11000
잔액 : 20000

 

 

메소드 오버라이딩 (=재정의)

: 부모 클래스의 메소드 물려받아 고쳐쓰는 것

 

cf. 메소드 오버로딩 : 같은 이름으로 여러 메소드 생성 (매개변수 개수, 타입, 순서 다를 때)

 

 

  •  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//마이너스 통장
public class CreditLineAccount extends Account{
    //필드
    int creditLine;    //마이너스 한도
    
    //생성자
    public CreditLineAccount(String accountNo, String ownerName, int balance, int creditLine) {
        super(accountNo, ownerName, balance);    //전달받는 매개변수 값
        this.creditLine=creditLine;
    }
    
    //메소드
    int withdraw(int amount) throws Exception {    
//deposit 메소드는 그대로, withdraw는 재정의=> 메소드 오버라이딩
        if (balance+creditLine<amount) {
            throw new Exception("인출이 불가능합니다.");
        }
        balance-=amount;
        return amount;
    }
}
cs

 

 

 

 

 

////

클래스 => 필드, 생성자, 메소드 생략해도 된다는 게 다 디폴트 생겨서 그런간가

아직 public, private / static 에 대한 확신이 없는듯 20번 문제에서도 뒤에선 왜 private static 인지 확신이 없고 public으로 하면 안되는지 궁금