객체지향의 특징
Jul 24, 2023
»
oop
객체 지향의 특징 4가지
캡슐화
객체(object)의 데이터(속성, attribute)와 행위(methods)를 하나로 묶고, 구현된 세부사항을 외부에 감추어 은닉한다. 데이터에 직접 접근하는 것을 제한하고, 데이터를 조작하려면 메서드를 통하도록 유도한다.
public class Car {
private float speed;
public float getSpeed() {
return this.speed;
}
public void setSpeed(float speed) {
this.speed = speed
}
}
추상화
객체들의 공통적인 특징을 추출하고 공통되는 속성이나 행위를 하나의 이름으로 표현한다. 특징을 추출하고 모델링할 때에는 객체가 가진 모든 기능을 구현하려 하기보다는 객체들간의 관계에 집중하여 구현한다.
public abstract class Shape {
public abstract double calculateArea();
}
public class Circle extends Shape {
private double radius;
@Override
public double calculateArea() {
return Math.PI * this.radius * this.radius;
}
}
public class Rectangle extends Shape {
private double length;
private double width;
@Override
public double calculateArea() {
return this.length * this.width;
}
}
다형성
같은 이름의 행위나 속성들이 다른 상황에서 다르게 동작할 수 있는 능력을 말한다. 다형성은 하나의 인터페이스를 통해 다양한 객체를 사용할 수 있게 해주어 코드의 재사용성과 확장성을 증가시킬 수 있다.
public class Calculator {
int add(int x, int y) {
int result = x + y;
return result;
}
double add(double x, double y) {
double result = x + y;
return result;
}
}
상속성
클래스가 다른 클래스의 속성과 행위를 물려받는 것을 의미한다. 상속을 통해 기존 클래스의 기능을 확장하거나 변경할 수 있다.
public class Animal {
public void makeSound() {
System.out.println("Animal makes a sound");
}
}
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Dog barks");
}
}
public class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Cat meows");
}
}
public class Main {
public static void main(String[] args) {
Animal animal1 = new Dog();
Animal animal2 = new Cat();
animal1.makeSound();
animal2.makeSound();
}
}