54
강강강강강 강강강강강강강 강 4 강 강강강 강강 2 강강강강강강강 1

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

  • Upload
    konane

  • View
    103

  • Download
    0

Embed Size (px)

DESCRIPTION

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

Citation preview

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

강원대학교 1

자바프로그래밍제 4 주

클래스 설계 2

자바프로그래밍

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

강원대학교 2

객체 자신에게 메소드 호출하기vs

다른 객체에게 메소드 호출하기

자바프로그래밍

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

강원대학교 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;}

BankAccount kims, 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

자바프로그래밍

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

강원대학교 4

public class BankAccount{ public void deposit(double amount) { double newBalance = balance + amount; balance = newBalance; } private double balance;}

BankAccount kims, 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

자바프로그래밍

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

강원대학교 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;}

BankAccount kims, 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

자바프로그래밍

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

강원대학교 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;}

BankAccount kims, 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

자바프로그래밍

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

강원대학교 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.calculate-

Bonus(amount);

}

public double getBalance() { return balance;

}

double calculateBonus(double amount){ return amount*BONUS_RATE;

}

}

자바프로그래밍

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

강원대학교 8

구성자에서 구성자 호출하기

자바프로그래밍

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

강원대학교 9

public BankAccount(){ balance = 0;}public BankAccount(double initialBalance){ balance = initialBalance;}

public BankAccount(){ this(0);}public BankAccount(double initialBalance){ balance = initialBalance;}

자바프로그래밍

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

강원대학교 10

인스턴스 멤버와 클래스 멤버

자바프로그래밍

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

강원대학교 11

인스턴스 변수와 클래스 변수• 인스턴스 변수 : 인스턴스마다 존재하는 변수• 클래스 변수 : 클래스 공통으로 하나만 존재하는

변수

public class BankAccount{private double balance;private int accountNumber;private static int numberOfAccounts = 0;

}

자바프로그래밍

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

강원대학교 12

인스턴스 변수와 클래스 변수• 인스턴스 변수 : 인스턴스마다 존재하는 변수• 클래스 변수 : 클래스 공통으로 하나만 존재하는

변수

public class BankAccount{private double balance;private int accountNumber;private static int numberOfAccounts = 0;

}

자바프로그래밍

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

강원대학교 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 num-ber accountNumber = ++numberOfAccounts; }

public int getAccountNumber() { return accountNumber; }

} BankAccountnumberOfAccounts: 0

자바프로그래밍

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

강원대학교 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);

BankAccountnumberOfAccounts: 1

balance: 100.0accountNumber:

1b1

자바프로그래밍

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

강원대학교 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);

BankAccountnumberOfAccounts: 0

balance: 100.0accountNumber:

1b1

balance: 200.0accountNumber:

2b2

자바프로그래밍

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

강원대학교 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

);

자바프로그래밍

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

강원대학교 17

클래스 메소드

• static 키워드가 메소드 앞에 붙으면 그 메소드는 개별 객체에 작용하지 않는다는 의미

• Static 메소드는 아래와 같은 형식으로 호출ClassName. methodName(parameters)

• Math 클래스 메소드들은 대부분 static 메소드

자바프로그래밍

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

강원대학교 18

The Math class

(-b + Math.sqrt(b*b - 4*a*c)) / (2*a)

자바프로그래밍

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

강원대학교 19

Mathematical Methods in Java

Math.sqrt(x) square root

Math.pow(x, y) power xy

Math.exp(x) ex

Math.log(x) natural logMath.sin(x), Math.cos(x), Math.tan(x)

sine, cosine, tangent (x in radian)

Math.round(x) closest integer to x Math.min(x, y), Math.max(x, y) minimum, maximum

자바프로그래밍

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

강원대학교 20

맥락에 맞게 사용해야 함• 인스턴스 메소드에서 인스턴스 변수와 인스턴스

메소드에 직접 접근 가능• 인스턴스 메소드에서 클래스 변수와 클래스

메소드에 직접 접근 가능• 클래스 메소드에서 클래스 변수와 클래스

메소드에 직접 접근 가능• 클래스 메소드에서 인스턴스 변수와 인스턴스

메소드에 직접 접근 불가능

자바프로그래밍

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

강원대학교 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 numberO-fAccounts;}public static void main(String[] args) {

BankAccount account = new BankAccount(100.0);account.deposit(100.0);withdraw(100.0); -------

System.out.println(BankAccount.getNumberOfAccounts());}

}

자바프로그래밍

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

강원대학교 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

자바프로그래밍

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

강원대학교 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));

}}

자바프로그래밍

Page 24: 자바프로그래밍 제  4 주 클래스 설계  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));}

}

자바프로그래밍

Page 25: 자바프로그래밍 제  4 주 클래스 설계  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)); // 같은 클래스 내}

}

자바프로그래밍

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

강원대학교 26

Constants( 상수 ): static fi-nal

• 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 클래스 밖에서 사용

자바프로그래밍

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

강원대학교 27

접근성• private – 같은 클래서 내에서만 접근 가능• (package) – 같은 패키지 내에서만 접근 가능• protected – 같은 패키지 , 혹은

서브클래스에서 접근 가능• public – 누구나 접근 가능

자바프로그래밍

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

강원대학교 28

클래스 멤버에의 접근성• 외부로 노출시켜야 할 멤버는 public• 내부 기능을 위한 멤버는 private

• 멤버 : 메소드와 필드 (, inner classes and interfaces)

자바프로그래밍

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

강원대학교 29

Fields 에의 접근성

• 필드 변수에의 접근성 (accessibility)public int i; // 누구나 i 에 접근할 수 있음int i; // 같은 패키지 안에서 접근할 수 있음private int i; // 같은 클래스 안에서만 접근할 수 있음

• 일반적으로 클래스 외부에서 클래스 내의 변수에 접근하는 것은 정보은닉 원칙에 어긋나므로 이를 허용하지 않도록 private 로 선언

필드 변수는 통상 private 로 선언 !

자바프로그래밍

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

강원대학교 30

Fields• public 클래스 필드에 직접 접근하려면 아래와 같이 할 수 있음

Student s = new Student();System.out.println(s.name);s.name = “ 배철수” ;

이런 방법은 권장하지 않음필드 변수는 private 로 선언하고필드 변수는 그 객체가 지원하는 메소드를 통해서 변경하는 것이 좋음

class Studnent{

public String name = “ 철수” ; // 필드 }

자바프로그래밍

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

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:컴파일 에러 !

자바프로그래밍

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

강원대학교 32

메소드에의 접근성• 외부로 노출시켜야 할 메소드는 public• 내부 기능을 위한 메소드는 private

자바프로그래밍

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

강원대학교 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;}

}

자바프로그래밍

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

강원대학교 34

기타

자바프로그래밍

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

강원대학교 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”

자바프로그래밍

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

강원대학교 36

Concatenation in Print Statements• 아래 두 프로그램은 동일 결과

System.out.print("The total is ");System.out.println(total);

System.out.println("The total is " + total);

자바프로그래밍

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

강원대학교 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]

자바프로그래밍

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

강원대학교 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

자바프로그래밍

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

강원대학교 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);

자바프로그래밍

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

강원대학교 40

Substrings• String 클래스의 메소드

String greeting = "Hello, World!";String sub = greeting.substring(0, 5); // sub is "Hello"

inclusive exclusive

자바프로그래밍

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

강원대학교 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();

자바프로그래밍

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

강원대학교 42

• 객체를 생성하기 위해서는 키워드 new 생성자를 사용 Rectangle r = new Rectangle(1, 1, 2, 3);

• 그러나 String 객체만은 예외적으로String s = " 스트링“과 같이 간편하게 생성하는 것도 가능

• 특수문자new line – "\n"탭 – "\t"따옴표 – "\""

자바프로그래밍

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

강원대학교 43

Scanner scanner = new Scanner(System.in);String id = scanner.next();if (id.matches("[12]")) ...

정규식 (regular expression)[a-z]

입력 값을 검사하는 법

자바프로그래밍

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

강원대학교 44

Color c = panel.getBackground();if(c.equals(Color.black)) ...

if(panel.getBackground().equals(Color.black)) ...

이렇게 써도 된다 .

자바프로그래밍

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

강원대학교 45

경과 시간 측정하는 법long start = System.currentTimeMillis();....long duration = (System.currentTimeMillis()-start)/

1000;

자바프로그래밍

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

강원대학교 46

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}

switch 문장 형식

자바프로그래밍

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

강원대학교 47

Random Numbers and Simula-tions

• 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);

자바프로그래밍

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

강원대학교 48

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

자바프로그래밍

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

강원대학교 49

File Die.java19: /**20: Simulates a throw of the die21: @return the face of the die 22: */23: public int cast()24: {25: return 1 + generator.nextInt(sides);26: }27: 28: private Random generator;29: private int sides;30: }

자바프로그래밍

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

강원대학교 50

File DieTester.java01: /**02: This program simulates casting a die ten times.03: */04: public class DieTester05: {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: }

자바프로그래밍

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

강원대학교 51

Wrappers

자바프로그래밍

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

강원대학교 52

Wrapper 인스턴스

자바프로그래밍

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

강원대학교 53

자동포장기능 (Auto-boxing)

• 기본 데이터타입과 wrapper 클래스 간 자동 변환

Double d = new Double(29.95); // 기존 방법Double d = 29.95; // auto-boxing

double x = d.doubleValue(); // 기존 방법double x = d; // auto-unboxing

자바프로그래밍

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

강원대학교 54

자동포장기능 (Auto-boxing)

① d 의 포장을 벗겨 double 타입으로 만듦 ② 1 을 더함 ③ 결과를 Double 타입 객체로 포장 ④ 레퍼런스를 e 가 포장된 Double 타입

객체를 가리키도록 함

Double d = new Double(3.1);Double e = d + 1.0;

자바프로그래밍