1 / 54

자바프로그래밍 제 4 주 클래스 설계 2

자바프로그래밍 제 4 주 클래스 설계 2. 객체 자신에게 메소드 호출하기 vs 다른 객체에게 메소드 호출하기. public class BankAccount { public BankAccount () public BankAccount (double initialBalance ) public void deposit(double amount) public void withdraw(double amount )

konane
Download Presentation

자바프로그래밍 제 4 주 클래스 설계 2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 자바프로그래밍제 4주클래스 설계 2 강원대학교

  2. 객체 자신에게 메소드 호출하기vs다른 객체에게 메소드 호출하기 강원대학교

  3. public class BankAccount{ public BankAccount() public BankAccount(double initialBalance)public void deposit(double amount) public void withdraw(double amount) public void transfer(double amount, BankAccount other) public double getBalance() private double balance; } BankAccountkims, moms;kims = new BankAccount(); moms = new BankAccount(1000.0);moms.deposit(2000.0); moms.transfer(500.0, kims); System.out.println(moms.getBalance()); System.out.println(kims.getBalance()); moms kims 강원대학교

  4. public class BankAccount{public void deposit(double amount) { double newBalance = balance + amount; balance = newBalance; } private double balance; } BankAccountkims, moms;kims = new BankAccount(); moms = new BankAccount(1000.0);moms.deposit(2000.0); moms.transfer(500.0, kims); System.out.println(moms.getBalance()); System.out.println(kims.getBalance()); moms kims 강원대학교

  5. public class BankAccount{public void deposit(double amount) { double newBalance = balance + amount; balance = newBalance; } public void withdraw(double amount){...} public void transfer(double amount, BankAccount other) { withdraw(amount); other.deposit(amount); } private double balance; } BankAccountkims, moms;kims = new BankAccount(); moms = new BankAccount(1000.0);moms.deposit(2000.0); moms.transfer(500.0, kims); System.out.println(moms.getBalance()); System.out.println(kims.getBalance()); moms kims 강원대학교

  6. public class BankAccount{public void deposit(double amount) { double newBalance = balance + amount; balance = newBalance; } public void transfer(double amount, BankAccount other) { this.withdraw(amount) other.deposit(amount); } private double balance; } BankAccountkims, moms;kims = new BankAccount(); moms = new BankAccount(1000.0);moms.deposit(2000.0); moms.transfer(500.0, kims); System.out.println(moms.getBalance()); System.out.println(kims.getBalance()); moms kims 강원대학교

  7. class Account { private double balance = 0.0; final double BONUS_RATE = 0.01; public void deposit(double amount) { balance = amount + calculateBonus(amount); // 혹은 balance = amount + this.calculateBonus(amount); } public double getBalance() { return balance; } double calculateBonus(double amount){ return amount*BONUS_RATE; } } 강원대학교

  8. 구성자에서구성자 호출하기 강원대학교

  9. public BankAccount(){ balance = 0;}public BankAccount(double initialBalance){ balance = initialBalance;} public BankAccount(){this(0);}public BankAccount(double initialBalance){ balance = initialBalance;} 강원대학교

  10. 인스턴스 멤버와 클래스 멤버 강원대학교

  11. 인스턴스 변수와 클래스 변수 • 인스턴스 변수: 인스턴스마다 존재하는 변수 • 클래스 변수: 클래스 공통으로 하나만 존재하는 변수 public class BankAccount{ private double balance; private int accountNumber; private static int numberOfAccounts = 0; } 강원대학교

  12. 인스턴스 변수와 클래스 변수 • 인스턴스 변수: 인스턴스마다 존재하는 변수 • 클래스 변수: 클래스 공통으로 하나만 존재하는 변수 public class BankAccount{ private double balance; private int accountNumber; private static int numberOfAccounts = 0; } 강원대학교

  13. public class BankAccount{ private double balance; private int accountNumber; private static int numberOfAccounts = 0; public BankAccount(double initialBalance){ balance = initialBalance; // increment number of Accounts and assign account number accountNumber = ++numberOfAccounts; } public int getAccountNumber() { return accountNumber; } } BankAccount numberOfAccounts: 0 강원대학교

  14. public class BankAccount { private double balance; private int accountNumber; private static int numberOfAccounts = 0; public BankAccount(double initialBalance){ balance = initialBalance; accountNumber = ++numberOfAccounts; } } BankAccount b1 = new BankAccount(100.0); balance: 100.0 accountNumber: 1 BankAccount numberOfAccounts: 1 b1 강원대학교

  15. public class BankAccount { private double balance; private int accountNumber; private static int numberOfAccounts = 0; public BankAccount(double initialBalance){ balance = initialBalance; accountNumber = ++numberOfAccounts; } } BankAccount b1 = new BankAccount(100.0); BankAccount b2 = new BankAccount(200.0); balance: 100.0 accountNumber: 1 b1 BankAccount numberOfAccounts: 0 balance: 200.0 accountNumber: 2 b2 강원대학교

  16. 클래스 변수에접근하는 법 public class BankAccount{ double balance; int accountNumber; static int numberOfAccounts = 0; } BankAccount b1 = new BankAccount(100.0); // 인스턴스변수에는 레퍼런스를 통해 접근 System.out.println(b1.balance); // 클래스변수에는 클래스이름을 통해 접근 System.out.println(BankAccount.numberOfAccounts); 강원대학교

  17. 클래스메소드 • static 키워드가 메소드 앞에 붙으면 그 메소드는 개별 객체에 작용하지 않는다는 의미 • Static 메소드는 아래와 같은 형식으로 호출 ClassName. methodName(parameters) • Math 클래스 메소드들은 대부분 static 메소드 강원대학교

  18. The Math class (-b + Math.sqrt(b*b - 4*a*c)) / (2*a) 강원대학교

  19. Mathematical Methods in Java 강원대학교

  20. 맥락에 맞게 사용해야 함 • 인스턴스 메소드에서 인스턴스 변수와 인스턴스 메소드에 직접 접근 가능 • 인스턴스 메소드에서 클래스 변수와 클래스 메소드에 직접 접근 가능 • 클래스 메소드에서 클래스 변수와 클래스 메소드에 직접 접근 가능 • 클래스 메소드에서 인스턴스 변수와 인스턴스 메소드에 직접 접근 불가능 강원대학교

  21. public class BankAccount { private double balance; private int accountNumber; private static int numberOfAccounts = 0; public BankAccount(double initialBalance) { balance = initialBalance; accountNumber = ++numberOfAccounts; } public void deposit(double amount) {balance = amount + amount;} public void withdraw(double amount) { balance = balance – amount;} public static int getNumberOfAccounts() {return numberOfAccounts;} public static void main(String[] args) { BankAccount account = new BankAccount(100.0); account.deposit(100.0); withdraw(100.0); ------- System.out.println(BankAccount.getNumberOfAccounts()); } } 강원대학교

  22. public class Adder { public int add(int a, int b) { return a + b; } public static void main(String[] args) { System.out.println(add(1, 2)); } } Cannot make a static reference to the non-static method add(int, int) from the type Adder 강원대학교

  23. public class Adder { public int add(int a, int b) { return a + b; } public static void main(String[] args) { Adder adder = new Adder(); System.out.println(adder.add(1, 2)); } } 강원대학교

  24. public class Adder { public static int add(int a, int b) { return a + b; } public static void main(String[] args) { System.out.println(Adder.add(1, 2)); } } 강원대학교

  25. public class Adder { public static int add(int a, int b) { return a + b; } public static void main(String[] args) { System.out.println(add(1, 2)); // 같은 클래스 내 } } 강원대학교

  26. Constants(상수): static final • static final constant는 다른 클래스에 의해 주로 사용됨 • static final constant는 아래와 같은 방법으로 사용 public class Math{ . . . public static final double E = 2.7182818284590452354; public static final double PI = 3.14159265358979323846;} double circumference = Math.PI * diameter; // Math 클래스 밖에서 사용 강원대학교

  27. 접근성 • private – 같은 클래서 내에서만 접근 가능 • (package) – 같은 패키지 내에서만 접근 가능 • protected – 같은 패키지, 혹은 서브클래스에서 접근 가능 • public – 누구나 접근 가능 강원대학교

  28. 클래스 멤버에의 접근성 • 외부로 노출시켜야 할 멤버는 public • 내부 기능을 위한 멤버는 private • 멤버: 메소드와 필드 (, inner classes and interfaces) 강원대학교

  29. Fields에의 접근성 • 필드 변수에의 접근성(accessibility) public inti; // 누구나 i에 접근할 수 있음 inti; // 같은 패키지 안에서 접근할 수 있음 private inti; // 같은 클래스 안에서만 접근할 수 있음 • 일반적으로 클래스 외부에서 클래스 내의 변수에 접근하는 것은 정보은닉 원칙에 어긋나므로 이를 허용하지 않도록 private로 선언  필드 변수는 통상 private로 선언! 강원대학교

  30. Fields • public 클래스 필드에 직접 접근하려면 아래와 같이 할 수 있음 Student s = new Student(); System.out.println(s.name); s.name = “배철수”; class Studnent { public String name = “철수”; // 필드 } 이런 방법은 권장하지 않음 필드 변수는 private로 선언하고 필드 변수는 그 객체가 지원하는 메소드를 통해서 변경하는 것이 좋음 강원대학교

  31. private instance field • private instance field에는 해당 클래스 내에서만 접근 가능하다. public class BankAccount {private double balance; public void deposit(double amount) { double newBalance = balance + amount;balance = newBalance;} } BankAccount maryAccount = new BankAccount(5000); maryAccount.balance = maryAccount.balance + 3000; Tester: 컴파일 에러! 강원대학교

  32. 메소드에의 접근성 • 외부로 노출시켜야 할 메소드는 public • 내부 기능을 위한 메소드는 private 강원대학교

  33. class Account { private double balance = 0.0; final double BONUS_RATE = 0.01; public void deposit(double amount) { balance = amount + calculateBonus(amount); } public double getBalance() { return balance; } // Account 내부에서만 사용되는 메소드 private double calculateBonus(double amount){ return amount*BONUS_RATE; } } 강원대학교

  34. 기타 강원대학교

  35. String Concatenation(문자열 연결) • Use the + operator: • 문자열을 다른 값과 + 연산자로 연결하면 다른 값은 자동으로 문자열로 변환됨 String name = "Dave";String message = "Hello, " + name; // message is "Hello, Dave" String a = "Agent";int n = 7;String bond = a + n; // bond is “Agent7” 강원대학교

  36. Concatenation in Print Statements • 아래 두 프로그램은 동일 결과 System.out.print("The total is ");System.out.println(total); System.out.println("The total is " + total); 강원대학교

  37. 객체를 출력하면 • 객체에 toString() 메소드가 호출되고 그 반환값이 출력됨 • 객체를 문자열과 + 연산자로 연결하면 • 객체에 toString() 메소드가 호출되고 그 반환값이 문자열과 연결됨 Rectangle r = new Rectangle(); System.out.println(r); // java.awt.Rectangle[x=0,y=0,width=0,height=0] Rectangle r = new Rectangle(); String s = r + ""; System.out.println(s); // java.awt.Rectangle[x=0,y=0,width=0,height=0] 강원대학교

  38. Strings and Numbers • Number (integer의 경우) 12 = 0000 000C (0000 0000 0000 0000 0000 0000 0000 1100)1024 = 0000 0400 (0000 0000 0000 0000 0000 0100 0000 0000) 1048576 = 0100 0000 (0000 0000 0001 0000 0000 0100 0000 0000) • String "12" = 0031 0032 "1024" = 0030 0030 0032 0034 "1048576" = 0031 0030 0034 0038 0035 0037 0036 강원대학교

  39. Converting between Strings and Numbers • Convert to number: • Convert to string: String str = “35”; String xstr = “12.3”; int n = Integer.parseInt(str);double x = Double.parseDouble(xstr); int n = 10; String str = "" + n;str = Integer.toString(n); 강원대학교

  40. Substrings • String 클래스의 메소드 String greeting = "Hello, World!";String sub = greeting.substring(0, 5); // sub is "Hello" inclusive exclusive 강원대학교

  41. Reading Input – Scanner 클래스 • Scanner 인스턴스를 만들고 이 객체에 적절한 입력 메소드 호출 • next reads a word (until any white space) • nextLine reads a line (until user hits Enter) Scanner in = new Scanner(System.in);System.out.print("Enter quantity: ");int quantity = in.next(); 강원대학교

  42. 객체를 생성하기 위해서는 키워드 new 생성자를 사용 Rectangle r = new Rectangle(1, 1, 2, 3); • 그러나 String 객체만은 예외적으로 String s = "스트링“ 과 같이 간편하게 생성하는 것도 가능 • 특수문자 new line –"\n" 탭 – "\t" 따옴표 –"\"" 강원대학교

  43. 입력 값을 검사하는 법 Scanner scanner = new Scanner(System.in); String id = scanner.next(); if (id.matches("[12]")) ... 정규식 (regular expression) [a-z] 강원대학교

  44. 이렇게 써도 된다. Color c = panel.getBackground(); if(c.equals(Color.black)) ... if(panel.getBackground().equals(Color.black)) ... 강원대학교

  45. 경과 시간 측정하는 법 long start = System.currentTimeMillis(); .... long duration = (System.currentTimeMillis()-start)/1000; 강원대학교

  46. switch 문장 형식 switch (expr) { // expr는 정수나 char 등의 타입! case c1: statements // do these if expr == c1 break; case c2: statements // do these if expr == c2 break; case c2: case c3: case c4: // Cases can simply fall thru. statements // do these if expr == any of c's break; . . . default: statements // do these if expr != any above } 강원대학교

  47. Random Numbers and Simulations • Random number generator • 주사위 (random number between 1 and 6) Random generator = new Random();int n = generator.nextInt(a); // 0 <= n < adouble x = generator.nextDouble(); // 0 <= x < 1 int d = 1 + generator.nextInt(6); 강원대학교

  48. File Die.java 01: import java.util.Random; 02: 03: /** 04: This class models a die that, when cast, lands on a 05: random face. 06: */ 07:public class Die 08: { 09: /** 10: Constructs a die with a given number of sides. 11: @param s the number of sides, e.g. 6 for a normal die 12: */ 13:public Die(int s) 14: { 15: sides = s; 16: generator = new Random(); 17: } 18: 강원대학교

  49. File Die.java 19: /** 20: Simulates a throw of the die 21: @return the face of the die 22: */ 23:public int cast() 24: { 25:return1 + generator.nextInt(sides); 26: } 27: 28:private Random generator; 29:private int sides; 30: } 강원대학교

  50. File DieTester.java 01: /** 02: This program simulates casting a die ten times. 03: */ 04:public class DieTester 05: { 06:public static void main(String[] args) 07: { 08: Die d = new Die(6); 09:final int TRIES = 10; 10:for (int i = 0; i < TRIES; i++) 11: { 12:int n = d.cast(); 13: System.out.print(n + " "); 14: } 15: System.out.println(); 16: } 17: } 강원대학교

More Related