Post

OOP 개념 알아보기

OOP 개념 알아보기

오늘은 OOP에 대한 기본적인 개념을 다시 잡고 가려고 정리해보았습니다.

클래스

데이터 필드와 메소드 필드를 가지는 오브젝트의 템플릿입니다.

오브젝트

프로그램에 직접 들어가는 클래스의 인스턴스입니다.

클래스에 쓴 함수로 오브젝트에서 값을 입력할 수 있습니다.

캡슐화

클래스의 보안을 제공하며, 다른 개발자들이 클래스안의 멤버와 메소드를 변경할 수 없게 도와줍니다.

상속

코드 재사용을 할 수 있는 부모 자식간의 관계입니다.

부모 클래스에서 존재하는 기능을 자식 클래스에서 쓸 수 있게 해줍니다.

다형성

자바에서는 오버로딩과 오버라이딩으로 표현가능합니다.

  • 오버로딩 : 같은 함수의 이름이지만 다른 인자로 다른 행동을 취함

  • 오버라이딩 : 같은 함수의 같은 인자이지만, 상속 관계에 다른 행동을 취함

가상화

가상 클래스에 있는 가상 메소드는 구형하지않고, 상속받는 자식 클래스에서 구현해야됩니다.

만약 컨셉만 구현하고 다른 개발자들이 따라주길 바랄 때 필요합니다.

실습 코드

1
2
3
4
public abstract class Car {
	public abstract void engine();
	public abstract void fuel();
}

추상 클래스에서 공통 메소드를 추상 메소드로 만듭니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class RealMinicar extends Car{
	
	private int price;
	
	public RealMinicar() {
		System.out.println("Running");
	}
	
	public RealMinicar(String s) {
		System.out.println("Running " + s);
	}
	
	public void MethodCheck() {
		System.out.println("this is original system output");
	}
	

	@Override
	public void engine() {
		System.out.println("old engine");
	}

	@Override
	public void fuel() {
		System.out.println("Oil");
	}

	public int getPrice() {
		return price;
	}

	public void setPrice(int price) {
		this.price = price;
	}

}

추상 클래스를 상속받아서 구현하고, 생성자 오버로드와 오버라이드를 구현할 메소드를 작성합니다.

캡슐화를 위해 getter와 setter를 만들어서 변수에 접근하고 설정하는 메소드를 작성합니다.

1
2
3
4
5
public class RealMinicar_A extends RealMinicar {
	public void MethodCheck() {
		System.out.println("this is custom system output");
	}
}

상속받으면 부모 클래스의 메소드를 사용할 수 있으며, 오버라이드를 통해 내용을 수정할 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Main {
	public static void main(String[] args) {
		RealMinicar test1 = new RealMinicar("speed car");
		
		RealMinicar_A test2 = new RealMinicar_A();
		
		test1.engine();
		test1.fuel();
		
		test2.engine();
		test2.fuel();
		
		test1.setPrice(300);
		
		System.out.println(test2.getPrice());
		
		test2.setPrice(200);
		
		System.out.println(test2.getPrice());
		
		test1.MethodCheck();
		
		test2.MethodCheck();
	}
}

메인 클래스에서 클래스 타입의 오브젝트(객체)를 만들어서 인자를 통해 데이터 필드에 접근합니다.

This post is licensed under CC BY 4.0 by the author.