JAVA 객체 지향 프로그래밍(OOP)
1. 객체 지향 프로그래밍(Object Oriented Programming : OOP)
여러 개의 독립된 단위, 즉 객체들의 모임으로 파악하고자 하는 것
각각의 객체는 메세지를 주고 받고 데이터를 처리
- 절차 지향 프로그래밍(Procedural Programming)
프로그램을 수행하는 일련의 절차나 함수를 중심으로 구성
대표적인 언어로 C언어가 있다.
1.1 객체지향 프로그래밍 특징
캡슐화 | Encapsulation |
상속 | Inheritance |
추상화 | Abstract |
다형성 | Polymorphism |
- 캡슐화 (Encapsulation)
관련된 필드(속성)와 메소드(기능)를 하나로 묶고, 실제 구현 내용을 외부로 감추는 기법(정보은닉)
만일의 상황(타인이 외부에서 조작)을 대비해서 특정 속성이나 메소드를 사용자가 조작할 수 없도록 숨겨 놓은 것.
외부에서는 공개된 메소드(기능)를 통해 접근할 수 있다.
- 추상화 (Abstract)
객체에서 공통된 속성과 행위를 추출하는 기법
상세한 정보는 무시하고 필요한 정보들만 간추려서 구성
- 상속 (Inheritance)
이미 작성된 클래스(상위클래스)의 특성을 그대로 이어받아 새로운 클래스(하위클래스)를 생성하는 기법
기존 코드를 그대로 재사용하거나 재정의 > 재사용 + 확장
- 다형성 (Polymorphism)
사전적 의미 '다양한 형태로 나타날 수 있는 능력'
같은 기능(메소드)를 호출하더라도 객체에 따라 다르게 동작하는 것
상위클래스의 동작을 하위클래스에서 다시 정의하여 사용하는 것 또한 다형성으로 볼 수 있다.
Overriding(오버라이딩)
package oop;
public class Tv {
// 클래스의 구조 - 필드와 메소드로 이루어져 있다.
// 필드 - 변수
int channel; // 채널
int volume; // 볼륨
int light; // 밝기
boolean power; // 전원
int resolution; // 해상도
2. 클래스(Class)
객체(인스턴스)가 가지는 필드(속성)와 메소드(기능)를 묶어둔 하나의 단위
현실의 객체를 표현하기 위한 설계도
2.1 클래스 구조
Field (속성) | Method (행동) |
이름 | 걷다 |
키 | 먹다 |
나이 | 자다 |
성별 | 말하다 |
머리색 | 싸우다 |
눈동자색 | 생각하다 |
public class Tv {
// 클래스의 구조 - 필드와 메소드로 이루어져 있다.
// 필드 - 변수
int channel; // 채널
int volume; // 볼륨
int light; // 밝기
boolean power; // 전원
int resolution; // 해상도
// 객체 기능정의 - 메소드
public void channelUp() {
channel++;
if (channel == 1000) // 최대 채널 999로 초과시 채널 1번이동
channel = 1;
}
public void channelDown() {
channel--;
if (channel == 0) //최소 채널 1로 0이하로 감소시 채널 999번 이동
channel = 999;
}
public void volumeUp() {
volume++;
if (volume == 31) {
System.out.println("최대 볼륨 입니다. ");
volume = 30;
} else if (volume > 24) {
System.out.println("청력을 보호하기 위해서 소리를 줄여주세요.");
}
}
public void volumeDown() {
volume--;
if (volume == -1) {
System.out.println("최소 볼륨 입니다. ");
volume = 0;
}
}
public void powerOnOff() {
power = !power;
}
2.2 Class 예제 저금통 프로그램
Step 1 다음과 같은 내용의 클래스를 작성하시오
저금통 클래스 |
속성(필드) |
금액(money) |
기능(메소드) |
돈을 넣는다(deposit) 돈을 인출한다(wothdraw) 잔액을 보여준다(showMoney) |
package oop;
public class PiggyBank {
int money;
public int deposit(int depositMoney) {
if (depositMoney < 0) System.out.println("잘못된 입력 입니다.");
else money += depositMoney;
return money;
}
public int withdraw(int withdraw) {
if (withdraw < 0) System.out.println("잘못된 입력 입니다.");
if (money < withdraw) System.out.println("출금이 불가능 합니다.");
else money -= withdraw;
return money;
}
public void showMoney() {
System.out.println("현재 잔액은 " + money + " 입니다.");
}
}
Step 2 main 클래스에 작성
1번 클릭 시 저금할 금액을 입력하세요.
2번 클릭 시 인출할 금액을 입력하세요.
3번 클릭 시 금액을 확인하세요.
4번 클릭 시 종료하는 프로그램을 만드세요.
package oop;
import java.util.Scanner;
public class Piggy_main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PiggyBank PB = new PiggyBank();
while (true) {
System.out.print("1.저금 2.인출 3.금액확인 4.종료 >> ");
int ckeak = sc.nextInt();
if (ckeak == 1) {
System.out.print("저금할 금액을 입력하세요 : ");
int depositMoney = sc.nextInt();
PB.deposit(depositMoney);
} else if (ckeak == 2) {
System.out.print("인출한 금액을 입력하세요 : ");
int withdraw = sc.nextInt();
PB.withdraw(withdraw);
} else if (ckeak == 3) {
PB.showMoney();
} else if (ckeak == 4) {
System.out.println("종료 합니다.");
break;
} else {
System.out.println("잘못된 번호 입니다.");
}
}
sc.close();
}
}
2.3 Class 예제 학생정보 관리 프로그램 만들기
Step 1 학생의 정보를 Student클래스를 작성하세요.
자료형태 | 변수 이름 | 설명 |
String | name | 이름 |
String | number | 학번 |
int | age | 나이 |
int | scoreJava | java 점수 |
int | scoreWeb | web 점수 |
int | scoreAndroid | Android 점수 |
public class Student {
String name; // 이름
String number; // 학번
int age; // 나이
int scoreJava; // 자바 점수
int scoreWeb; // 웹 점수
int scoreAndroid;// 안드로이드 점수
// 클래스명과 동일(대소문자 구분)
// 접근제한자/ 리턴타입은 없음(void도 아님)/ 클래스명과 동일
Step 2 show()메소드를 Student클래스 안에 작성하세요.
public Student(String name, String number, int age, int scoreJava, int scoreWeb, int scoreAndroid) {
this.name = name;
this.number = number;
this.age = age;
this.scoreJava = scoreJava;
this.scoreWeb = scoreWeb;
this.scoreAndroid = scoreAndroid;
}
public void show() {
System.out.println(name + "님 안녕하세요.");
System.out.println("[ " + number + ", " + age + "살 ]");
System.out.println(name + "님의 Java 점수는 " + scoreJava + "점 입니다.");
System.out.println(name + "님의 Web 점수는 " + scoreWeb + "점 입니다.");
System.out.println(name + "님의 Android 점수는 " + scoreAndroid + "점 입니다.");
System.out.println("=".repeat(50));
}
Step3 main()메소드에 호출하여 학생 정보를 출력하세요.
public class Student_main {
public static void main(String[] args) {
Student aaa = new Student("에이군","20230001",20,50,89,77);
Student bbb = new Student("비이양","20230002",20,90,100,70);
aaa.show();
bbb.show();
}
}