Object Oriented Programing
: 객체를 정의하고 객체 간의 상호작용을 프로그램으로 구현하는 것
변수
), 기능(메서드
)을 표현// Student.java
public class Student {
String studentName;
int grade;
int money;
// 1.2.1. 학생 객체와 버스 객체 간의 협업이 발생되는 부분
public void takeBus(Bus bus) {
bus.take(1000);
System.out.println(studentName + "학생이 " + bus.busNumber + "번 버스를 탔습니다.");
}
// 1.2.2. 학생 객체와 지하철 객체 간의 협업이 발생되는 부분
public void takeSubway(Subway subway) {
subway.take(1200);
System.out.println(studentName + "학생이 " + subway.lineNumber + "번 노선을 탔습니다.");
}
}
// Bus.java
public class Bus {
int busNumber;
int passengerCount;
int money;
public void take(int money) {
passengerCount++;
this.money += money;
}
}
// Subway.java
public class Subway {
int lineNumber;
int passengerCount;
int money;
public void take(int money) {
passengerCount++;
this.money += money;
}
}
takeBus(Bus) 메서드
Student 클래스
)이 버스비를 지불하므로 인하여 비용(money 변수
)이 발생Bus 클래스
)의 인원수(passengerCount 변수
)와 수입(money 변수
)이 증가takeSubway(Subway) 메서드
Student 클래스
)이 지하철 요금을 지불하므로 인하여 비용(money 변수
)이 발생Subway 클래스
)의 인원수(passengerCount 변수
)와 수입(money 변수
)이 증가
// Customer.java
public class Customer {
protected int customerId;
protected String customerName;
protected String customerGrade;
int bonusPoint;
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerGrade() {
return customerGrade;
}
public void setCustomerGrade(String customerGrade) {
this.customerGrade = customerGrade;
}
public int getBonusPoint() {
return bonusPoint;
}
public void setBonusPoint(int bonusPoint) {
this.bonusPoint = bonusPoint;
}
}
// Customer.java
public class Customer {
protected int customerId;
protected String customerName;
protected String customerGrade;
int bonusPoint;
double bonusRatio;
public Customer(int customerId, String customerName) {
this.customerId = customerId;
this.customerName = customerName;
customerGrade = "SILVER";
bonusRatio = 0.01;
}
public int calcPrice(int price) {
bonusPoint += price * bonusRatio;
return price;
}
public String showCustomerInfo() {
return customerName + "님의 등급은 " + customerGrade + "이며, 보너스 포인트는 " + bonusPoint + "원입니다.";
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerGrade() {
return customerGrade;
}
public void setCustomerGrade(String customerGrade) {
this.customerGrade = customerGrade;
}
public int getBonusPoint() {
return bonusPoint;
}
public void setBonusPoint(int bonusPoint) {
this.bonusPoint = bonusPoint;
}
}
// GoldCustomer.java
public class GoldCustomer extends Customer {
public GoldCustomer(int customerId, String customerName) {
super(customerId, customerName);
// 아래 변수들이 오버라이딩 됨
customerGrade = "GOLD";
bonusRatio = 0.05;
}
@Override
public int calcPrice(int price) {
return super.calcPrice(price);
}
@Override
public String showCustomerInfo() {
return super.showCustomerInfo();
}
}
// VIPCustomer.java
public class VIPCustomer extends Customer {
int agentId;
double saleRatio;
public VIPCustomer(int customerId, String customerName, int agentId) {
super(customerId, customerName);
// 아래 변수들이 오버라이딩 됨
customerGrade = "VIP";
bonusRatio = 0.05;
saleRatio = 0.1;
this.agentId = agentId;
}
// VIP등급 고객의 경우, 할인율이 적용되므로 상위클래스의 calcPrice를 재정의 -> 메서드 오버라이딩 발생
@Override
public int calcPrice(int price) {
bonusPoint += price * bonusRatio;
return price - (int)(price * saleRatio);
}
public int getAgentId() {
return agentId;
}
}
✔️ 포함(Composite)을 이용한 재사용 ✔️
- 한 클래스가 다른 클래스를 멤버로 포함하는 것
ex) Circle 클래스가 Point 클래스를 포함- 실제로 포함을 이용하여 재사용을 많이 함
- Has-a 관계라고도 말함
// Point.java public class Point { private int x; private int y; public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } } // Circle.java public class Circle { Point point; private int radius; public Circle() { point = new Point(); } }
// Car.java
public interface Car {
public void turnOn();
public void drive();
public void wiper();
public void turnOff();
}
// ManualCar.java
public class ManualCar implements Car {
@Override
public void turnOn() {
System.out.println("운전자가 시동을 켭니다.");
}
@Override
public void drive() {
System.out.println("운전자가 수동으로 방향을 변경합니다.");
}
@Override
public void wiper() {
System.out.println("운전자가 와이퍼를 작동합니다.");
}
@Override
public void turnOff() {
System.out.println("운전자가 시동을 끕니다.");
}
}
// AICar.java
public class AICar implements Car {
@Override
public void turnOn() {
System.out.println("자동으로 시동이 켜집니다.");
}
@Override
public void drive() {
System.out.println("자동으로 방향이 변경됩니다.");
}
@Override
public void wiper() {
System.out.println("비 또는 눈이 내리면 자동으로 와이퍼가 작동됩니다.");
}
@Override
public void turnOff() {
System.out.println("자동으로 시동이 꺼집니다.");
}
}
❓ 가상 메서드(Virtual Method) ❓
- 상속 관계에서 오버라이딩 된 메서드는 선언한 클래스형이 아닌 생성된 인스턴스의 메서드가 호출되는 것
ex) 선언한 클래스: 동물 클래스(Animal
) / 생성된 인스턴스: 사람 클래스의 인스턴스(new Human()
)Animal human = new Human();
- 자바의 모든 메서드는 가상 메서드
// Animal.java
public class Animal {
public void move() {
System.out.println("동물이 움직입니다.");
}
}
// Human.java
public class Human extends Animal {
@Override
public void move() {
System.out.println("사람이 두 발로 걷습니다.");
}
public void readBook() {
System.out.println("사람이 책을 읽습니다.");
}
}
// Tiger.java
public class Tiger extends Animal {
@Override
public void move() {
System.out.println("호랑이가 네발로 뜁니다.");
}
public void hunting() {
System.out.println("호랑이가 사냥을 합니다.");
}
}
// Eagle.java
public class Eagle extends Animal {
@Override
public void move() {
System.out.println("독수리가 하늘을 납니다.");
}
public void flying() {
System.out.println("독수리가 날개짓을 하며 하늘을 날아갑니다.");
}
}
// AnimalTest.java
public class AnimalTest {
public static void main(String[] args) {
AnimalTest test = new AnimalTest();
// 업캐스팅
test.moveAnimal(new Human()); // Animal human = new Human(); 과 동일
test.moveAnimal(new Tiger()); // Animal tiger = new Tiger(); 과 동일
test.moveAnimal(new Eagle()); // Animal eagle = new Eagle(); 과 동일
}
public void moveAnimal(Animal animal) {
animal.move(); // 업캐스팅 시 선언 클래스가 아닌 생성된 인스턴스의 메서드를 호출 -> 다형성이 구현됨!!
}
}
잘 정리하였네요. 후루룩 읽었읍니다. 보고. 저도 . 배우겠네요. 감사함미다.