Java

객체 지향 프로그래밍 OOP 특징 | 캡슐화, 추상화, 상속, 다형성

Karla Ko 2023. 9. 13. 18:37
728x90

 

OOP(Object Oriented Programming)

  • 문제를 여러 개의 객체 단위로 나눠 작업하는 방식으로 객체들이 서로 상호작용하는 프로그래밍 이론
  • 객체들의 모임으로 파악하는 것
  • 여러 독립적인 부품들의 조합, 즉 객체들의 유기적인 협력과 결합으로 파악하고자 하는 컴퓨터 프로그래밍의 패러다임을 의미
  • 클래스를 이용하여 관련있는 처리(기능) 부분과 데이터 부분을 하나의 객체(인스턴스)로 묶어 생성하여 사용

 

캡슐화 (Encapsulation)

  • 데이터와 코드의 형태를 함께 묶어 외부에서 알 수 없도록 하고, 데이터의 구조와 역할/기능을 하나의 캡슐형태로 구현하는 방법
  • 캡슐화의 중요한 목적은 변수를 private 으로 선언하여 데이터를 보호하는 것
  • 보호된 변수는 getter()/setter() 메소드를 통해서만 간접적으로 접근을 허용하는 것
  • (이 캡슐형태를 사용하는 데 필요한 인터페이스만 외부에 공개하는 것)
  • 숨기는 목적은 클래스 내부 구현의응집도(cohesion)를 높이고 외부 다른 클래스와의 결합도(coupling)을 낮추는 데 있음

캡슐화를 하기 위해서 Java의 경우 접근 제어자를 활용합

클래스 접근 제어자

  • dafault: 동일 패키지의 클래스(class)에만 인스턴스(객체)를 생성 가능
  • public: 다른 패키지에서 인스턴스(객체)를 생성 가능

메소드 접근 제어자

  • private: 동일한 클래스 안에서만 접근이 가능, this를 사용하는 것들은 외부에서 접근 불가능, 상속 불가
  • default: 접근제어나가 없는 형태로 동일한 패키지 안에서만 접근이 가능
  • protected: 동일한 패키지 안에서 사용 가능, 다른 패키지라도 상속받은 클래스에는 접근이 가능
  • public: 모든 객체에서 접근 가능

더보기
class Person {

    // private variables, cannot be directly accessed by other class.
    private String name;
    private int age;
    private String dateOfBirth;

    // class constructor
    Person (String n, int a, String d){
        this.name = n;
        this.age = a;
        this.dateOfBirth = d;
    }

    // public methods to get the variables information.
    public String getName() {
        return name;
    }
    public int getAge(){
        return age;
    }
    public String getDateOfBirth() {
        return dateOfBirth;
    }

    // public methods to set variables to new values.
    public void setName(String newName){
        this.name = newName;
    }
    public void setAge(int newAge){
        this.age = newAge;
    }
    public void setDateOfBirth(String newD){
        this.dateOfBirth = newD;
    }
}

 

추상화 (Abstraction)

  •  객체의 공통적인 속성과 기능을 추출하여 정의하는 것
  • 실제로 존재하는 객체들을 프로그램으로 만들기 위해 공통 특성을 파악해 필요없는 특성을 제거하는 과정
  • 객체들은 실제의 모습이지만, 클래스는 객체들이 어떤 특징이 있어야 한다고 정의하는 추상화된 개념
더보기
// abstract class starts with an abstract keyword
abstract class Shape {
    // regular variable 
    String typeOfShape;

    // abstract methods with no body, implementation leaves for the sub class.
    abstract void draw();
    abstract double area();

    // constructor of this abstract class.
    public Shape(String t){
        typeOfShape = t;
    }

    // concrete methods with bodies.

    public String getTypeOfShape() {
        return typeOfShape;
    }
    public String toString() {
        return "Unknown";
    }
}

class Circle extends Shape {
    double radius;
    public Circle (double r, String t){
        super(t);
        this.radius = r;
    }
    
    // overriden methods
    void draw () {
        System.out.println("This is a cirlce");
    }

    double area() {
        return Math.PI * radius * radius;
    }

    public String toString() {
        return "The area of this " + this.typeOfShape + " is: " + area(); 
    }
    
}

 

상속 (Inheritance)

  • 기존 상위 클래스에 기능을 가져와 재사용할 수 있으면서도 동시에 새로운 하위 클래스에 새로운 기능도 추가할 수 있는 것
  • 재사용성 증가, 코드의 중복 감소
  • OOP에서는 상속을 한 클래스를 부모 클래스, 상속을 받은 클래스를 자식 클래스라고 표현
  • 자식 객체를 생성할 때 부모 클래스의 속성들을 자동으로 물려받기 때문에 자식 클래스에서 또 정의할 필요가 없음
슈퍼클래스(부모 클래스)
슈퍼클래스는 자식 클래스가 기능을 상속받을 수 있는 클래스

자식 클래스(파생 클래스)
자식 클래스는 다른 클래스를 상속받는 클래스
더보기
// super class Product 
class Product{
    int productId = 20;
    String name = "Cool Product";
    double price = 39.0d;
}

// subclass ElectricProduct
class ElectricProduct extends Product{
    double voltage = 34;
    double power = 12;
}

// subclass FoodProduct
class FoodProduct extends Product {
    String date = "03-20-2019";
    String expiredDate = "01-19-2020";
}

// subclass CeramicProduct
class CeramicProduct extends Product {
    String type = "A";
}

class Main {
    public static void main(String[] args){
        Product a = new Product();
        ElectricProduct b = new ElectricProduct();
        FoodProduct c = new FoodProduct();
        CeramicProduct d = new CeramicProduct();
        
        System.out.println("Product: "+ a.productId + " " + a.name + " " + a.price);
        System.out.println("Electric Product: " + b.name + " " + b.name + " " + b.price + " " + b.voltage + " " + b.power);
        System.out.println("Food Product: "+ c.productId + " " + c.name + " " + c.price + " " + c.date + " " + c.expiredDate);
        System.out.println("Ceramic Product: "+ d.productId + " " + d.name + " " + d.price + " " + d.type);
    }
}

 

Product:  20 Cool Product 39.0
Electric Product: Cool Product Cool Product 39.0 34.0 12.0
Food Product: 20 Cool Product 39.0 03-20-2019 01-19-2020
Ceramic Product: 20 Cool Product 39.0 A

 

다형성 (Polymorphism)

  • 상속과 연관있는 개념
  • 한 객체가 상속을 통해 기능을 확장하거나 변경하여 다른 여러 형태(객체)로 재구성 되는 것
  • 한 부모 밑에서 태어난 자식을이 조금씩 다르다는 것
오버로딩(Overloading)
하나의 클래스 안에서같은 이름의 메소드를 사용하지만, 각 메소드마다 다른 용도로 사용되는 것
(메소드명은 같지만, 파라미터 타입/갯수가 다른 형태)단, Reutrn Type은 같아야 함.

오버라이딩(Orverriding)
하위(자식) 클래스가 상위(부모) 클래스에서 만들어진 메소드를 재정의 하는 것을 의미
더보기
class Overloadding {
    public void aMethod() {
        System.out.println("A method with no parameter!");
    }
    public void aMethod(int a, String b, double c){
        System.out.println("This method has 3 parameters: " + a + " " + b + " " + c);
    }
    public void aMethod(String a, int b){
        System.out.println("This method has 2 parameter: " + a + " " + b);
    }
    public void aMethod(double a){
        System.out.println("This method has 1 parameter: " + a);
    }
}
class Main{
    public static void main(String[] args){
        Overloadding x = new Overloadding();
        x.aMethod();
        x.aMethod(22.4);
        x.aMethod("A", 3);
        x.aMethod(13, "C", 27.5);
    }
}
// superclass, has one method speak
class Animal {
    void speak() {
        System.out.println("I am saying something! Can you hear?");
    }
}

// class Dog extends Animal and overrides the speak method
class Dog extends Animal {
    void speak() {
        System.out.println("Woof!");
    }
}

// class Cat extends Animal and overrides the speak method
class Cat extends Animal {
    void speak() {
        System.out.println("Meow!");
    }
}
class Main {
    public static void main(String[] args){
        Animal a = new Animal();
        a.speak();
        Animal b = new Dog();
        b.speak();
        Animal c = new Cat();
        c.speak();
    }
}
728x90