[Java] OOP 4가지

전혜린·2023년 2월 13일
2

1. OOP란?

Object Oriented Programing

: 객체를 정의하고 객체 간의 상호작용을 프로그램으로 구현하는 것



1.1. 객체란?

  • 현실세계에 존재하는 유무형의 모든 것
  • 하나의 클래스 안에 속성(변수), 기능(메서드)을 표현
    ex) 학생 클래스, 버스 클래스, 지하철 클래스



1.2. 객체 간의 상호작용이란?

// 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 변수)이 증가






2. OOP 특징 4가지

2.1. Encapsulation(캡슐화)

  • 객체의 속성과 기능을 하나로 묶음
  • 데이터를 외부에서 직접 접근하지 못하도록 은닉하는 것
  • 접근제어자로 접근 가능 범위를 제한
    ex) public, protected(상속 관계에서는 public), private, default
  • getter/setter 메서드로 외부의 간접적인 접근을 허용
// 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;
	}
}



2.2. inheritance(상속)

  • 일반적인 클래스의 기능을 가져와 클래스를 구체화하는 것
  • 일반적인 클래스와 구체적인 클래스의 관계
    ex) 일반적인 클래스: 고객 클래스 / 구체적인 클래스 : 일반 고객 클래스, VIP 고객 클래스
  • Is-a 관계라고도 말함
  • 단순 재사용을 위해 사용하는 방법이 절대 아님 ! ! !
// 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();
	}
}



2.3. Abstraction(추상화)

  • 객체의 공통적인 속성과 기능을 추출하여 정의하는 것
  • 인터페이스에서 공통 속성과 기능을 선언하고 하위 클래스에서 구현하여 구체적인 내용을 구현
    ex) 인터페이스: 자동차 인터페이스 / 하위 클래스: 수동 자동차 클래스 ,자율주행자동차 클래스
  • 클라이언트 소스에서 인터페이스의 구현체를 몰라도 기능 사용이 가능
// 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("자동으로 시동이 꺼집니다.");
    }
}



2.4. Polymorphism(다형성)

  • 하나의 코드로 여러가지 결과를 만들 수 있는 것
  • 상속 -> 업캐스팅 -> 가상메서드의 원리로 인하여 오버라이딩이 된 메서드가 호출되어 다형성이 구현됨

    ❓ 가상 메서드(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();	// 업캐스팅 시 선언 클래스가 아닌 생성된 인스턴스의 메서드를 호출 -> 다형성이 구현됨!!
    }
}
profile
개발새발 혤린이

9개의 댓글

comment-user-thumbnail
2023년 2월 15일

잘 정리하였네요. 후루룩 읽었읍니다. 보고. 저도 . 배우겠네요. 감사함미다.

1개의 답글
comment-user-thumbnail
2023년 2월 15일

★★★★★
웬만한 강의보다 더 이해가 잘되네요.
재방문 의사 있습니다.

1개의 답글
comment-user-thumbnail
2023년 2월 15일

와 설명 맛집이네요!!!!

1개의 답글