강의 4 - 강원대학교

Download Report

Transcript 강의 4 - 강원대학교

자바프로그래밍
제 4주
클래스 설계 2
자바프로그래밍
강원대학교
1
객체 자신에게 메소드 호출하기
vs
다른 객체에게 메소드 호출하기
자바프로그래밍
강원대학교
2
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;
}
moms
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());
자바프로그래밍
강원대학교
kims
3
public class BankAccount
{
public void deposit(double amount)
{
double newBalance = balance + amount;
balance = newBalance;
}
private double balance;
}
moms
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());
자바프로그래밍
강원대학교
kims
4
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;
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());
자바프로그래밍
강원대학교
kims
5
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;
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());
자바프로그래밍
강원대학교
kims
6
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;
}
}
자바프로그래밍
강원대학교
7
구성자에서 구성자 호출하기
자바프로그래밍
강원대학교
8
public BankAccount()
{
balance = 0;
}
public BankAccount(double initialBalance)
{
balance = initialBalance;
}
public BankAccount()
{
this(0);
}
public BankAccount(double initialBalance)
{
balance = initialBalance;
}
자바프로그래밍
강원대학교
9
인스턴스 멤버와 클래스 멤버
자바프로그래밍
강원대학교
10
인스턴스 변수와 클래스 변수
• 인스턴스 변수: 인스턴스마다 존재하는 변수
• 클래스 변수: 클래스 공통으로 하나만 존재하는
변수
public class BankAccount{
private double balance;
private int accountNumber;
private static int numberOfAccounts = 0;
}
자바프로그래밍
강원대학교
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;
public BankAccount(double initialBalance){
balance = initialBalance;
// increment number of Accounts and assign account number
accountNumber = ++numberOfAccounts;
}
public int getAccountNumber() {
return accountNumber;
}
}
BankAccount
numberOfAccounts: 0
자바프로그래밍
강원대학교
13
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
balance: 100.0
accountNumber: 1
numberOfAccounts: 1
b1
자바프로그래밍
강원대학교
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);
BankAccount b2 = new BankAccount(200.0);
BankAccount
b1
balance: 100.0
accountNumber: 1
b2
balance: 200.0
accountNumber: 2
numberOfAccounts: 0
자바프로그래밍
강원대학교
15
클래스 변수에 접근하는 법
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);
자바프로그래밍
강원대학교
16
클래스 메소드
• static 키워드가 메소드 앞에 붙으면 그 메소드는 개별 객체에 작용하
지 않는다는 의미
• Static 메소드는 아래와 같은 형식으로 호출
ClassName. methodName(parameters)
• Math 클래스 메소드들은 대부분 static 메소드
자바프로그래밍
강원대학교
17
The Math class
(-b + Math.sqrt(b*b - 4*a*c)) / (2*a)
자바프로그래밍
강원대학교
18
Mathematical Methods in Java
Math.sqrt(x)
square root
Math.pow(x, y)
power xy
Math.exp(x)
ex
Math.log(x)
natural log
Math.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
자바프로그래밍
강원대학교
19
맥락에 맞게 사용해야 함
• 인스턴스 메소드에서 인스턴스 변수와 인스턴스
메소드에 직접 접근 가능
• 인스턴스 메소드에서 클래스 변수와 클래스 메
소드에 직접 접근 가능
• 클래스 메소드에서 클래스 변수와 클래스 메소
드에 직접 접근 가능
• 클래스 메소드에서 인스턴스 변수와 인스턴스
메소드에 직접 접근 불가능
자바프로그래밍
강원대학교
20
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());
}
}
자바프로그래밍
강원대학교
21
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
자바프로그래밍
강원대학교
22
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));
}
}
자바프로그래밍
강원대학교
23
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));
}
}
자바프로그래밍
강원대학교
24
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)); // 같은 클래스 내
}
}
자바프로그래밍
강원대학교
25
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 클래스 밖에서 사용
자바프로그래밍
강원대학교
26
접근성
• private – 같은 클래서 내에서만 접근 가능
• (package) – 같은 패키지 내에서만 접근 가능
• protected – 같은 패키지, 혹은 서브클래스에서
접근 가능
• public – 누구나 접근 가능
자바프로그래밍
강원대학교
27
클래스 멤버에의 접근성
• 외부로 노출시켜야 할 멤버는 public
• 내부 기능을 위한 멤버는 private
• 멤버: 메소드와 필드
(, inner classes and interfaces)
자바프로그래밍
강원대학교
28
Fields에의 접근성
• 필드 변수에의 접근성 (accessibility)
public int i;
// 누구나 i에 접근할 수 있음
int i;
// 같은 패키지 안에서 접근할 수 있음
private int i;
// 같은 클래스 안에서만 접근할 수 있음
• 일반적으로 클래스 외부에서 클래스 내의 변수에 접근하는 것은 정보
은닉 원칙에 어긋나므로 이를 허용하지 않도록 private로 선언
 필드 변수는 통상 private로 선언!
자바프로그래밍
강원대학교
29
Fields
• public 클래스 필드에 직접 접근하려면 아래와 같이 할 수 있음
class Studnent
{
public String name = “철수”; // 필드
}
Student s = new Student();
System.out.println(s.name);
s.name = “배철수”;
이런 방법은 권장하지 않음
필드 변수는 private로 선언하고
필드 변수는 그 객체가 지원하는 메소드를 통해서 변경하는 것이 좋음
자바프로그래밍
강원대학교
30
private instance field
• private instance field에는 해당 클래스 내에서만 접근 가능하다.
public class BankAccount
{
private double balance;
public void deposit(double amount) {
double newBalance = balance + amount;
balance = newBalance;
}
}
Tester:
BankAccount maryAccount = new BankAccount(5000);
maryAccount.balance = maryAccount.balance + 3000; 컴파일 에러!
자바프로그래밍
강원대학교
31
메소드에의 접근성
• 외부로 노출시켜야 할 메소드는 public
• 내부 기능을 위한 메소드는 private
자바프로그래밍
강원대학교
32
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;
}
}
자바프로그래밍
강원대학교
33
기타
자바프로그래밍
강원대학교
34
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”
자바프로그래밍
강원대학교
35
Concatenation in Print Statements
• 아래 두 프로그램은 동일 결과
System.out.print("The total is ");
System.out.println(total);
System.out.println("The total is " + total);
자바프로그래밍
강원대학교
36
• 객체를 출력하면
• 객체에 toString() 메소드가 호출되고 그 반환값이 출력
됨
Rectangle r = new Rectangle();
System.out.println(r);
// java.awt.Rectangle[x=0,y=0,width=0,height=0]
• 객체를 문자열과 + 연산자로 연결하면
• 객체에 toString() 메소드가 호출되고 그 반환값이 문자
열과 연결됨
Rectangle r = new Rectangle();
String s = r + "";
System.out.println(s);
// java.awt.Rectangle[x=0,y=0,width=0,height=0]
자바프로그래밍
강원대학교
37
Strings and Numbers
• Number (integer의 경우)
12 =
1024 =
1048576 =
0000 000C (0000 0000 0000 0000 0000 0000 0000 1100)
0000 0400 (0000 0000 0000 0000 0000 0100 0000 0000)
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
자바프로그래밍
강원대학교
38
Converting between Strings and
Numbers
• Convert to number:
String str = “35”;
String xstr = “12.3”;
int n = Integer.parseInt(str);
double x = Double.parseDouble(xstr);
• Convert to string:
int n = 10;
String str = "" + n;
str = Integer.toString(n);
자바프로그래밍
강원대학교
39
Substrings
• String 클래스의 메소드
String greeting = "Hello, World!";
String sub = greeting.substring(0, 5); // sub is "Hello"
inclusive exclusive
자바프로그래밍
강원대학교
40
Reading Input – Scanner 클래스
Scanner in = new Scanner(System.in);
System.out.print("Enter quantity: ");
int quantity = in.next();
• Scanner 인스턴스를 만들고 이 객체에 적절한 입력 메소드 호출
– next reads a word (until any white space)
– nextLine reads a line (until user hits Enter)
자바프로그래밍
강원대학교
41
• 객체를 생성하기 위해서는 키워드 new 생성자를 사용
Rectangle r = new Rectangle(1, 1, 2, 3);
• 그러나 String 객체만은 예외적으로
String s = "스트링“
과 같이 간편하게 생성하는 것도 가능
• 특수문자
new line – "\n"
탭 – "\t"
따옴표 – "\""
자바프로그래밍
강원대학교
42
입력 값을 검사하는 법
Scanner scanner = new Scanner(System.in);
String id = scanner.next();
if (id.matches("[12]")) ...
정규식 (regular expression)
[a-z]
자바프로그래밍
강원대학교
43
이렇게 써도 된다.
Color c = panel.getBackground();
if(c.equals(Color.black)) ...
if(panel.getBackground().equals(Color.black)) ...
자바프로그래밍
강원대학교
44
경과 시간 측정하는 법
long start = System.currentTimeMillis();
....
long duration = (System.currentTimeMillis()-start)/1000;
자바프로그래밍
강원대학교
45
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
}
자바프로그래밍
강원대학교
46
Random Numbers and Simulations
• Random number generator
Random generator = new Random();
int n = generator.nextInt(a); // 0 <= n < a
double x = generator.nextDouble(); // 0 <= x < 1
• 주사위 (random number between 1 and 6)
int d = 1 + generator.nextInt(6);
자바프로그래밍
강원대학교
47
File Die.java
01:
02:
03:
04:
05:
06:
07:
08:
09:
10:
11:
12:
13:
14:
15:
16:
17:
18:
import java.util.Random;
/**
This class models a die that, when cast, lands on a
random face.
*/
public class Die
{
/**
Constructs a die with a given number of sides.
@param s the number of sides, e.g. 6 for a normal die
*/
public Die(int s)
{
sides = s;
generator = new Random();
}
자바프로그래밍
강원대학교
48
File Die.java
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30: }
/**
Simulates a throw of the die
@return the face of the die
*/
public int cast()
{
return 1 + generator.nextInt(sides);
}
private Random generator;
private int sides;
자바프로그래밍
강원대학교
49
File DieTester.java
01:
02:
03:
04:
05:
06:
07:
08:
09:
10:
11:
12:
13:
14:
15:
16:
17:
/**
This program simulates casting a die ten times.
*/
public class DieTester
{
public static void main(String[] args)
{
Die d = new Die(6);
final int TRIES = 10;
for (int i = 0; i < TRIES; i++)
{
int n = d.cast();
System.out.print(n + " ");
}
System.out.println();
}
}
자바프로그래밍
강원대학교
50
Wrappers
자바프로그래밍
강원대학교
51
Wrapper 인스턴스
자바프로그래밍
강원대학교
52
자동포장기능 (Auto-boxing)
• 기본 데이터타입과 wrapper 클래스 간 자동 변
환
Double d = new Double(29.95); // 기존 방법
Double d = 29.95; // auto-boxing
double x = d.doubleValue(); // 기존 방법
double x = d; // auto-unboxing
자바프로그래밍
강원대학교
53
자동포장기능 (Auto-boxing)
Double d = new Double(3.1);
Double e = d + 1.0;
① d의 포장을 벗겨 double 타입으로 만듦
② 1을 더함
③ 결과를 Double 타입 객체로 포장
④ 레퍼런스를 e가 포장된 Double 타입 객체를
가리키도록 함
자바프로그래밍
강원대학교
54