Module 07: 객체지향 프로그래밍 기본
시작 프로그래밍! -> 분수의 사칙연산을 메소드로 구현하기
state = data
EX> class(= Rational)를 하나 생성 -> 객체(= Rational의 인스턴스)를 여러 개 찍어냄
==> 붕어빵 틀을 만듦 -> 붕어빵을 찍어냄
객체의 3가지 특징:
- identity(ID): 한 객체는 다른 객체와 구분될 수 있음
- Behavior(행위): 객체는 작업을 수행함
- State(상태): 객체는 상태를 포함함
추상화 = 불필요한 것을 선택하고 제거하는 과정(동작 이름만 중요하게 보자!)
- 어떤 것이 중요하고 어떤 것이 중요하지 않은지에 대한 판단
- 어떤 것이 중요한지에 대해 초점을 맞추고 판단
- 어떤 것이 신뢰할 수 없고 필요 없는지에 대한 판단
- 캡슐화는 추상화의 강력한 도구
추상화를 잘하기 위한 방법이 캡슐화! ( => 정보 은닉의 방법 X)
캡슐화 = 정보 보안을 강력하게 하기 위한 방법
- 데이터와 기능을 단일 개체로 결합
- 개체의 모든 멤버(메소드, 변수 등)에 대한 접근 가시성 제어
- 메소드는 public, 외부에서 볼 수 있음
- 데이터는 private, 내부에서만 볼 수 있음
숨기면 좋은점? 내부의 변경 사항을 외부 사용자가 알 수 없고, 관계없이 사용 O
캡슐화를 하는 2가지 목적 = 1. 사용 제어 2. 변경의 영향 최소화
객체 내부에서 static 데이터를 제외한 모든 데이터 항목 = 각각의 객체에 대한 정보
Static :
정적 메소드(Static Method)는 정적 데이터에만 액세스 할 수 있음
정적 메소드는 클래스에서 호출됨. 객체가 아님
main이 정적 메소드가 되면 런타임이 클래스의 인스턴스를 만들 수가 없음 (동적 메소드(non-static 메소드)는 객체에서만 호출 O)
public 과 private 을 사용하여 캡슐화하는 것은 프로그래머에게 달려 있음! Java는 이를 강제 X
getter
- 내부의 멤버변수에 저장된 값을 외부로 리턴
- 메개변수는 없고, 리턴값만 있는 메서드로 정의
- 메소드 이름은 주로 getXXX() 메서드 형식으로 지정(XXX은 해당 멤버변수의 변수명을 사용)
setter
- 외부로부터 데이터를 전달받아 멤버변수에 저장
- 매개변수만 있고, 리턴값은 없는 메서드로 정의
static 메소드에 값을 하나 할당하면, 다른 메소드와 그 값을 공유하며 사용 O
BigDecimal
내부적으로 수를 십진수로 저장하여 아주 작은 수과 큰 수의 연산에 대해 거의 무한한 정밀도를 보장
객체지향 특징 4가지 : 1. 추상화 2. 캡슐화 3. 상속성 4. 다형성
상속 : 같은 타입(분류)의 클래스와의 관계 ( = is a kind of)
: 나자신을 추상화 단계를 높인다고 해도 부모님이 될 수 X
: 클래스의 동작과 속성에서 추가된 동작과 속성을 가지도록 모델링 O
단일 상속(Single Inheritance): 하나의 기본 클래스에서 파생됨
다중 상속(Multiple Inheritance): 하나 또는 그 이상의 클래스에서 파생됨
abstract
= 자식 클래스에서 반드시 오버라이딩해야만 사용할 수 있는 메소드
= 다른 클래스에게 상속해주기 위해 지정
실제 다형성 구현 -> 늦은 바인딩
EX> 클래스 구조
class 이름 {
클래스 변수(상태);
메소드(동작) { ... }
}































// Lab7-1. CreateAccount_BankAccount.java
import java.math.*;
public class BankAccount {
private long accountNumber;
private String ownerName;
private BigDecimal balance;
public void setData(long accountNumber, String ownerName, BigDecimal balance) {
this.accountNumber = accountNumber;
this.ownerName = ownerName;
this.balance = balance;
}
public long getNumber() {
return this.accountNumber;
}
public String getOwnerName() {
return this.ownerName;
}
public BigDecimal getBalance() {
return this.balance;
}
}
class CreateAccount {
public static BankAccount createNewBankAccount(long accountNumber, String ownerName, BigDecimal balance) {
BankAccount newAccount = new BankAccount();
newAccount.setData(accountNumber, ownerName, balance);
return newAccount;
}
public static void main(String[] args) {
BankAccount bankAccount = CreateAccount.createNewBankAccount(1, "Vesper Lind", new BigDecimal("0.0"));
printBankAccount(bankAccount);
}
public static void printBankAccount(BankAccount account) {
System.out.println("Account Number: " + account.getNumber());
System.out.println("Owner Name: " + account.getOwnerName());
System.out.println("Balance: " + account.getBalance());
}
}
// Lab7-2. AccountNumbers_BankAccount.java
import java.math.*;
public class BankAccount {
private long accountNumber;
private String ownerName;
private BigDecimal balance;
private static long nextAccountNumber;
private static long nextNumber() {
return nextAccountNumber++;
}
public void setData(String ownerName, BigDecimal balance) {
this.accountNumber = nextNumber();
this.ownerName = ownerName;
this.balance = balance;
}
public long getNumber() {
return this.accountNumber;
}
public String getOwnerName() {
return this.ownerName;
}
public BigDecimal getBalance() {
return this.balance;
}
}
class CreateAccount {
public static BankAccount createNewBankAccount(String ownerName, BigDecimal balance) {
BankAccount newAccount = new BankAccount();
newAccount.setData(ownerName, balance);
return newAccount;
}
public static void main(String[] args) {
BankAccount bankAccount = CreateAccount.createNewBankAccount("Vesper Lind", new BigDecimal("0.0"));
BankAccount bankAccount2 = CreateAccount.createNewBankAccount("Celine ", new BigDecimal("0.0"));
printBankAccount(bankAccount);
printBankAccount(bankAccount2);
}
public static void printBankAccount(BankAccount account) {
System.out.println("Account Number: " + account.getNumber());
System.out.println("Owner Name: " + account.getOwnerName());
System.out.println("Balance: " + account.getBalance());
}
}
// Lab7-3. MoreMethods_BankAccount.java
import java.math.*;
import java.util.Scanner;
public class BankAccount {
private long accountNumber;
private String ownerName;
private BigDecimal balance;
private static long nextAccountNumber;
private static long nextNumber() {
return nextAccountNumber++;
}
public void setData(String ownerName, BigDecimal balance) {
this.accountNumber = nextNumber();
this.ownerName = ownerName;
this.balance = balance;
}
public long getNumber() {
return this.accountNumber;
}
public String getOwnerName() {
return this.ownerName;
}
public BigDecimal getBalance() {
return this.balance;
}
public BigDecimal deposit(BigDecimal amount) {
this.balance = this.balance.add(amount);
return this.balance;
}
public boolean withDraw(BigDecimal amount) {
if (amount.compareTo(this.balance) == 1 || amount.compareTo(this.balance) == 0) {
return false;
}
else {
balance = balance.subtract(amount);
return true;
}
}
}
class CreateAccount {
public static BankAccount createNewBankAccount(String ownerName, BigDecimal balance) {
BankAccount newAccount = new BankAccount();
newAccount.setData(ownerName, balance);
return newAccount;
}
public static void TestDeposit(BankAccount account) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter amount to deposit: ");
BigDecimal amount = new BigDecimal(sc.next());
account.deposit(amount);
sc.close();
}
public static void TestWithDraw(BankAccount account) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter amount to withdraw: ");
BigDecimal amount = new BigDecimal(sc.next());
if(!account.withDraw(amount)) {
System.out.println("Insufficient funds!");
}
sc.close();
}
public static void main(String[] args) {
BankAccount bankAccount = CreateAccount.createNewBankAccount("Vesper Lind", new BigDecimal("0.0"));
printBankAccount(bankAccount);
TestDeposit(bankAccount);
printBankAccount(bankAccount);
TestWithDraw(bankAccount);
printBankAccount(bankAccount);
BankAccount bankAccount2 = CreateAccount.createNewBankAccount("Celine ", new BigDecimal("0.0"));
printBankAccount(bankAccount2);
TestDeposit(bankAccount2);
printBankAccount(bankAccount2);
TestWithDraw(bankAccount2);
printBankAccount(bankAccount2);
}
public static void printBankAccount(BankAccount account) {
System.out.println("Account Number: " + account.getNumber());
System.out.println("Owner Name: " + account.getOwnerName());
System.out.println("Balance: " + account.getBalance() + "\n");
}
}'✎NHN Academy | JAVA' 카테고리의 다른 글
| NHN Academy - 2024.08.28(Wed) (1) | 2024.08.28 |
|---|---|
| NHN Academy - 2024.08.27(Tue) (0) | 2024.08.27 |
| NHN Academy - 2024.08.23(Fri) (0) | 2024.08.23 |
| NHN Academy - 2024.08.22(Thu) (0) | 2024.08.22 |
| NHN Academy - 2024.08.21(Wed) (0) | 2024.08.21 |