💡 학습 목표
|
1. 객체지향 패러다임이란 뭘까?
객체지향 패러다임(Object-Oriented Paradigm)은 소프트웨어를 설계하고 구현하는 방법론 중 하나로, 실세계의 객체를 모델링하여 소프트웨어의 복잡성을 관리하고 코드의 재사용성을 높이는 데 중점을 둡니다. 이 패러다임의 핵심은 프로그램을 상호작용하는 객체들의 집합으로 보고, 각 객체는 자신의 데이터와 행위를 갖는 독립적인 엔티티로 취급하는 것입니다.
💡 "엔티티(Entity)"는 특정 속성과 행동을 가진 독립적인 단위 또는 객체를 의미합니다. |
객체지향 패러다임의 주요 원칙
- 캡슐화(Encapsulation): 객체는 데이터(변수)와 그 데이터를 조작하는 함수(메서드)를 하나로 묶습니다. 이를 통해 데이터 구조와 데이터를 조작하는 방법을 결합하여 데이터의 추상화를 가능하게 하고, 외부에서의 직접적인 접근을 제한합니다.
- 상속(Inheritance): 하나의 클래스가 다른 클래스의 특성을 물려받을 수 있는 메커니즘으로, 코드의 재사용성을 높이고, 중복을 줄이며, 유지 보수를 쉽게 합니다.
- 다형성(Polymorphism): 하나의 메서드나 클래스가 다양한 방식으로 동작하는 능력을 말합니다. 오버라이딩(Overriding)과 오버로딩(Overloading)은 다형성을 구현하는 일반적인 방법입니다.
- 추상화(Abstraction): 복잡한 현실의 개체를 단순화된 모델로 표현하는 것으로, 핵심적인 개념 또는 기능에만 집중하여 프로그램의 복잡성을 줄입니다.
지금 단계에서는 객체지향 프로그래밍이란 이렇게 기억해 봅시다.
💡 객체지향이란 객체와 객체간에 관계를 형성하고 상호작용하게 코드를 작성하는 것 |
package basic.ch09;
public class Bus {
int busNumber;
int passengerCount; // 승객 수
int money; // 수익금
// 강제성
public Bus(int number) {
// 객체 생성시에 제일 먼저 실행 되는 부분
busNumber = number;
}
// 승객을 태운다.
public void take(int pay) {
//money = money + pay;
money += pay;
//passengerCount = passengerCount + 1;
passengerCount++;
}
// 현재 상황을 보여주는 기능을 만들어 보자.
public void showInfo() {
System.out.println("버스 번호 : " + busNumber);
System.out.println("버스 승객수 : " + passengerCount);
System.out.println("버스 수익금 : " + money);
}
}
package basic.ch09;
public class Subway {
int lineNumber;
int passengerCount;
int money;
public Subway(int line) {
lineNumber = line;
}
// 지하철도 승객을 태우다.
public void take(int pay) {
money += pay;
passengerCount++;
}
// 현재 상황을 보여주는 기능을 만들어 보자.
public void showInfo() {
System.out.println("지하철 번호 : " + lineNumber);
System.out.println("지하철 승객수 : " + passengerCount);
System.out.println("지하철 수익금 : " + money);
}
}
package basic.ch009;
public class Student {
String name;
int money; // 소지금
public Student(String myName, int myMoney) {
name = myName;
money = myMoney;
}
// 학생이 버스를 탄다.
public void takeBus(Bus bus) {
// 어떻게 코드를 만들어야 할까?
bus.take(1500);
money = money - 1500;
}
// 학생이 지하철을 탄다.
// 상태창을 보여 준다.
public void showInfo() {
System.out.println("학생 이름 : " + name);
System.out.println("학생 소지금 : " + money);
}
}
실행 흐름 만들어 보기
package basic.ch09;
import java.util.Scanner;
public class GoingToSchool2 {
public static void main(String[] args) {
// 만들어진 설계된 클레스를 가지고 본인이 의도한 대로 실행에 흐름을 만들어 보자
// 스캐너를 활용해서 1번을 누르면 버스를 태워서 실해의 흐름을 만들고
// 2번을 누르면 지하철을 태우는 실행의 흐름을 만들어 봅시다.
Scanner sc = new Scanner(System.in);
Bus bus1 = new Bus(100); // 선언만 했음
Bus bus2 = new Bus(200); // 선언만 했음
Subway subway1 = new Subway(1);
Subway subway2 = new Subway(2);
Student s1 = new Student("황정민", 100_000);
Student s2 = new Student("최민식", 100_000);
// 만약 1, 2번 어떻게
while (true) {
System.out.print("1.버스, 2.지하철, 3.돈 없을 때");
int select = sc.nextInt();
if (select == 1) {
s1.takeBus(bus1);
s1.showInfo();
bus1.showInfo();
bus1.take(1500);
return;
} else if (select == 2) {
s2.takeBus(bus2);
s2.showInfo();
return;
} else if (select == 3) {
System.out.println("그냥 타지마라");
break;
}
}
} // end of main
} // end of class
클래스 설계 부터 실행 흐름
- 객체와 객체간에 상호작용할 수 있도록 코드를 설계하고 실행에 흐름을 만든다.
전사, 마법사 공격
전사
package basic.ch09;
public class Warrior {
String name;
int power;
int hp;
int depense;
// 생성자
public Warrior (String myName, int myPower, int myDepense) {
name = myName;
power = myPower;
hp = 100;
depense = myDepense;
}
// Warrior 공격을 하다
// Wizard 공격을 하다
public void attackWizard(Wizard wizard) {
System.out.println("마법사를 공격(" + this.power + ") 합니다.");
wizard.beAttacked(this.power);
}
public void beAttacked(int power) {
// 방어적 코드
if(hp <= 0) {
System.out.println("죽은자의 온기가 남아있습니다.");
return; // 실행에 흐름을 반환
}
hp = hp - power;
hp = hp + depense;
}
}
마법사
package basic.ch09;
public class Wizard {
String name;
int power;
int hp;
int depense;
public Wizard(String myName, int myPower, int myDepense) {
this.name = myName;
this.power = myPower;
this.depense = myDepense;
hp = 50;
}
// 전사를 공격하다
public void attackWarrior(Warrior warrior) {
System.out.println("전사를 공격(" + this.power + ") 합니다.");
warrior.beAttacked(this.power); // 호출
}
// 내가 공격을 받다.
public void beAttacked(int power) {
// 방어적 코드
System.out.println(this.depense + "데미지를 방어했습니다.");
if(hp <= 0) {
System.out.println("죽은자의 온기가 남아있습니다.");
return; // 실행에 흐름을 반환
}
hp = hp + depense;
hp = hp - power;
}
}
Main
package basic.ch09;
import java.util.Scanner;
public class MainTest {
//코드의 시작점 -> 실행의 흐름을 만들 수 있다.
public static void main(String[] args) {
Warrior warrior1 = new Warrior("바바", 10, 1);
Warrior warrior2 = new Warrior("고뇌바바", 30, 2);
Wizard wizard1 = new Wizard("소서", 20, 1);
System.out.println("전사가 마법사를 5번 공격합니다.");
System.out.println("전사가 마법사를 몇번 공격하시겠습니까");
Scanner sc = new Scanner(System.in);
int inputData = sc.nextInt();
for(int i = 0; i < inputData; i++) {
warrior1.attackWizard(wizard1);
}
System.out.println("마법사의 hp 확인 :" + wizard1.hp);
} // end of main
} // end of class
depense는 그냥 해본것
여기서 이것저것 더 넣어보며 흐름 찾기
구조이해
'Java > JAVA 2 - 객체지향 핵심' 카테고리의 다른 글
JAVA 2 - this 3가지 사용 방법 (0) | 2024.04.18 |
---|---|
JAVA 2 - 접근 제어 지시자 ( access modifier) (0) | 2024.04.17 |
JAVA 2 - 생성자(constructor) (0) | 2024.04.16 |
JAVA 2 - RunTime Data Area (0) | 2024.04.15 |
JAVA 2 - 메소드(method)와 변수 (0) | 2024.04.15 |