EEL2 LAB Week 5: 상속 ( 보충 ), 예외처리와스레드 1 Consider using the following Card class public class Card private String name; public Card() name = ""; public Card(String n) name = n; public String getname() return name; public boolean isexpired() return false; public String format() return "Card holder: " + name; Use this class as a superclass to implement a hierarchy of related classes: (DriverLicense is a sub-class of IDCard) Class IDCard CallingCard DriverLicense Data ID number Card number, PIN Expiration year Write declarations for each of the subclasses For each subclass, supply private instance variables Leave the bodies of the constructors and the format methods blank for now 2 Implement constructors for each of the three subclasses Each constructor should call the superclass constructor to set the name Here is one example: public IDCard(String n, String id) super(n); idnumber = id; 3 Replace the implementation of the format method for the three subclasses The methods should produce a formatted description of the card details The subclass methods should call the superclass format method to get the formatted name of the cardholder 4 Devise another class, Billfold, which contains slots for two cards, card1 and card2, a method void addcard(card) and a method String formatcards() The addcard method checks whether card1 is null If so, it sets card1 to the new card If not, it checks card2 If both cards are set already, the method has no effect Of course, formatcards invokes the format method on each non-null card and produces a string with the format
[card1 card2] What is your Billfold class? 5 Write a tester program that adds two objects of different subclasses of Card to a Billfold object Test the results of the formatcards methods What is the code for your BillfoldTester class? 6 The Card superclass defines a method isexpired, which always returns false This method was overridden in DriverLicense with an identical body, but the method is not appropriate for the driver license Supply a method body for DriverLicenseisExpired() that checks whether the driver license is already expired (ie, the expiration year is less than the current year) To work with dates, you can use the methods and constants supplied in abstract class Calendar which are inherited by the concrete class GregorianCalendar You create a Calendar as follows: GregorianCalendar calendar = new GregorianCalendar(); Then, you can obtain the current year using the constant CalendarYEAR and method get in GregorianCalendar The constant indicates that the method should return the current year By comparing the returned value with the expyear field in DriverLicense, you can determine if the card is expired The code below will retrieve the current year calendarget(calendaryear) 7 The ID card and the phone card don't expire What should you do to reflect this fact in your implementation? 8 Add a method getexpiredcardcount, which counts the number of expired cards in the billfold, to the Billfold class 9 Write a BillfoldTester class that populates a billfold with a phone card and an expired driver license Then call the getexpiredcardcount method Run your tester to verify that your method works correctly What is your tester class? 10 Implement tostring methods for the Card class and its three subclasses The methods should print: the name of the class the values of all instance variables (including inherited instance variables) Typical formats are: Card[name=Edsger W Dijkstra] CallingCard[name=Bjarne Stroustrup][number=4156646425,pin=2234]
Write the code for your tostring methods 11 Implement equals methods for the Card class and its three subclasses Cards are the same if the objects belong to the same class, and if the names and other information (such as the expiration year for driver licenses) match Give the code for your equals methods 12 Change the Card class and give protected access to name Would that change simplify the tostring method of the CallingCard class? How? Is this change advisable? 13 The BankAccount class has three methods with preconditions: 1) The constructor method (initial balance must not be negative) 2) The withdraw method (withdrawal amount must not be greater than the balance) 3) The deposit method (deposit amount must not be negative) Modify the code for the BankAccount class (shown below ) so that each of the three methods throws an IllegalArgumentException if the precondition is violated What is the code for your modified BankAccount class? 14 Using the following BankAccountDemo program, test the code in #13 and show the results import javautilscanner; public class BankAccountDemo public static void main(string[] args) Scanner in = new Scanner(Systemin); Systemoutprint("Initial balance: "); double initialbalance = innextdouble(); Systemoutprint("Amount to deposit: "); double amounttodeposit = innextdouble(); Systemoutprint("Amount to withdraw: "); double amounttowithdraw = innextdouble(); BankAccount account = new BankAccount(initialBalance); accountdeposit(amounttodeposit); accountwithdraw(amounttowithdraw); Systemoutprintln("New balance: " + accountgetbalance());
A bank account has a balance that can be changed by deposits and withdrawals public class BankAccount private double balance; Constructs a bank account with a zero balance public BankAccount() balance = 0; Constructs a bank account with a given balance @param initialbalance the initial balance public BankAccount(double initialbalance) balance = initialbalance; Deposits money into the bank account @param amount the amount to deposit public void deposit(double amount) balance = balance + amount; Withdraws money from the bank account @param amount the amount to withdraw public void withdraw(double amount) balance = balance - amount; Gets the current balance of the bank account @return the current balance public double getbalance() return balance; 15 What happens when you make the following errors with your revised BankAccount class? 1) Construct an account with a negative balance 2) Withdraw more money than the account balance 3) Enter an illegal input (such as "ten" instead of "10") 16 다음조건을만족하는클래스를구현하여테스트하는프로그램을작성 표준입력으로두개의정수를입력받아곱셈연산결과를출력
표준입력에서정수가아닌값이입력되면예외가발생하여실행이중단되는데, 이를예외 처리하여실행되도록 다음소스를참고 int x = 0, y = 0, z = 0; Scanner input = new Scanner(Systemin); Systemoutprintln(" 정수두개입력 : "); x = inputnextint(); y = inputnextint(); z = x * y; Systemoutprintf("%d * %d = %d %n", x, y, z); < 골격프로그램 > import javautilinputmismatchexception; import javautilscanner; public class Ex01 public static void main(string[] args) int x = 0, y = 0, z = 0; Scanner input = new Scanner(Systemin); Systemoutprintln(" 정수두개입력 : "); Systemoutprintf("%d / %d = %d %n", x, y, z); 17 다음조건을만족하도록클래스 BankAccount와이를테스트하는클래스 Ex02 프로그램을작성 새로운예외 InvalidWithdraw 를다음과같이구현 class InvalidWithdraw extends Exception private static final long serialversionuid = 1L; public InvalidWithdraw(String msg) super(msg); 클래스 BankAccount 는최저잔금을저장할수있는필드를지정하는생성자를제공하며, 메소드 deposit(momey) 은입금메소드이며, 메소드 withdraw(momey) 는출금메소드로인출요청금액이음수이거나최저잔금이하로인출을요청하면적당한메시지의예외 InvalidWithdraw 를발생시킨다 즉다음은최저잔고가 -100,000 원인은행계좌를만들어 500,000 원을인출하려는소스로서, 클래스 Ex02 의 main() 에서다음소스의예외처리를작성
BankAccount ba = new BankAccount( 100000); bawithdraw(500000); < 골격프로그램 > class InvalidWithdraw extends Exception class BankAccount int balance = 0; int diff = 0; int min; public BankAccount(int min) thismin = min; public void withdraw(int money) throws InvalidWithdraw public void deposit(int money) public class Ex02 public static void main(string args[]) BankAccount ba = new BankAccount( 100000); try bawithdraw(5000000); catch (InvalidWithdraw e) eprintstacktrace(); 18 위에서구현한클래스 InvalidWithdraw와 BankAccount를다음조건을만족하도록다시구현하여클래스 ex03에서테스트 클래스 Ex03 에서다음소스에문법오류가없도록예외 InvalidWithdraw 를비체크예외로 작성 public class Ex03 public static void main(string args[]) BankAccount ba = new BankAccount( 100000); badeposit(100000); bawithdraw(100000); bawithdraw(200000);
위클래스 Ex03 를실행하면다음과같이마지막문장에서예외가발생하도록 BankAccount 를 적절히구현 ( 단패키지와예외발생줄번호는달라도상관없음 ) 정상입금처리 : 입금금액 =100000, 잔금 =100000 정상출금처리 : 인출금액 =100000, 잔금 = 0 Exception in thread "main" ex03invalidwithdraw: 초과출금요구예외 at ex03bankaccountwithdraw(ex03java:24) at ex03ex03main(ex03java:45) 위클래스 Ex03 에서다시예외처리를구현 19 클래스 PrintTime 은인터페이스 Runnable 을구현하는클래스로지정된생성자의횟수만큼현재 시간과스레드이름을출력하는프로그램으로다음조건을만족하도록스레드 PrintTime 프로그램을 작성하여클래스 Ex04 의 main() 메소드에서테스트 클래스 Ex04 의 main() 메소드에서다음을실행하면다음과같이출력 PrintTime p1 = new PrintTime(3); Thread th1 = new Thread(p1, " 안녕하세요!"); th1setpriority(threadmax_priority 1); th1start(); PrintTime p2 = new PrintTime(6); Thread th2 = new Thread(p2, " 반갑습니다 "); th2setpriority(threadnorm_priority 1); th2start(); 순위 : 4 Sat Jul 07 20:28:56 KST 2012 반갑습니다 순위 : 9 Sat Jul 07 20:28:56 KST 2012 안녕하세요! 순위 : 9 Sat Jul 07 20:28:57 KST 2012 안녕하세요! 순위 : 4 Sat Jul 07 20:28:57 KST 2012 반갑습니다 순위 : 4 Sat Jul 07 20:28:57 KST 2012 반갑습니다 순위 : 9 Sat Jul 07 20:28:57 KST 2012 안녕하세요! 순위 : 4 Sat Jul 07 20:28:58 KST 2012 반갑습니다 순위 : 4 Sat Jul 07 20:28:58 KST 2012 반갑습니다 순위 : 4 Sat Jul 07 20:28:59 KST 2012 반갑습니다 < 골격프로그램 > import javautildate; class PrintTime implements Runnable
public class Ex04 public static void main(string[] args) PrintTime p1 = new PrintTime(3); Thread th1 = new Thread(p1, " 안녕하세요!"); th1setpriority(threadmax_priority 1); th1start(); PrintTime p2 = new PrintTime(6); Thread th2 = new Thread(p2, " 반갑습니다 "); th2setpriority(threadnorm_priority 1); th2start();