소개
캡슐화 (Encapsulation) 는 객체와 관련된 연산과 데이터를 함께 묶는 가방과 같습니다. 다형성 (Polymorphism) 은 객체가 여러 형태를 취할 수 있는 능력을 말합니다. 이 랩에서는 캡슐화와 다형성이 어떤 모습인지 살펴보겠습니다.
다형성 (Polymorphism)
다형성은 다양한 방식으로 단일 작업을 수행할 수 있게 해주는 객체 지향 프로그래밍 (OOP) 기능 중 하나입니다. 컴파일 시간에 해결되는 다형성은 정적 다형성 (static polymorphism) 또는 **컴파일 타임 다형성 (compile-time polymorphism)**이라고 합니다 (오버로딩 (overloading) 이 이 유형에 해당). 런타임 중에 해결되는 다형성은 **런타임 다형성 (runtime polymorphism)**이라고 합니다 (오버라이딩 (overriding) 이 이 유형에 해당). 다형성은 또한 객체가 여러 형태를 취할 수 있는 기능을 제공합니다. OOP 에서 다형성의 매우 일반적인 사용 사례는 부모 클래스 참조가 자식 클래스 객체를 참조하는 경우입니다. 하나 이상의 IS-A 테스트를 통과할 수 있는 모든 Java 객체는 *다형적 (polymorphic)*으로 간주됩니다. 참조 변수는 선언된 유형의 객체 또는 선언된 유형의 하위 유형의 객체를 참조할 수 있습니다. 참조 변수는 클래스 유형 또는 인터페이스 유형으로 선언될 수 있습니다. 상속의 경우는 다형성의 한 형태입니다. 왜냐하면 동물의 행동과 특징에는 여러 종류가 있기 때문입니다. 하지만 여기서는 또 다른 형태의 다형성을 소개합니다.

예시:
/home/labex/project/polymorphismTest.java 파일에 다음 코드를 작성합니다.
// we declare an interface life, it has some methods, we just omit them.
interface life{}
// and declare a class to realize polymorphism, the inner content, we just ignore that for this case.
class Animal{}
// we declare a Human class to use class of Animal and the life interface.
class Human extends Animal implements life{}
public class polymorphismTest{
public static void main(String[] args){
Human human = new Human(); // instantiate a Human object
// Human has direct or indirect inheritance relationship with Animal, Object
// Human implements life interface, so the instanceof expression returns true
System.out.println("human is instance of Human? " + (human instanceof Human));
System.out.println("human is instance of Animal? " + (human instanceof Animal));
System.out.println("human is instance of life? " + (human instanceof life));
System.out.println("human is instance of Object? " + (human instanceof Object));
}
}
출력:
다음 명령을 사용하여 polymorphismTest.java 파일을 실행합니다.
javac /home/labex/project/polymorphismTest.java
java polymorphismTest
출력을 확인합니다.
human is instance of Human? true
human is instance of Animal? true
human is instance of life? true
human is instance of Object? true
캡슐화 (Encapsulation)
**캡슐화 (Encapsulation)**는 프로그램의 세부 사항을 숨길 수 있게 해주는 개념입니다. 다른 호출자는 프로그램이 어떻게 작동하는지 알 필요 없이 프로그램이 무엇을 제공할 수 있는지 알면 됩니다. 캡슐화는 개발을 단순화합니다. 이는 데이터 (변수) 와 알고리즘 (메서드 코드) 을 묶는 메커니즘입니다. 캡슐화에서 클래스의 변수는 다른 클래스에서 숨겨지며 해당 클래스의 메서드를 통해서만 접근할 수 있습니다. 따라서 *데이터 은닉 (data hiding)*이라고도 합니다. 일반적으로 클래스 필드는 private 으로 선언되며, getter/setter 메서드를 사용하여 데이터에 접근하고 제어합니다. 우리는 다른 클래스에 기능을 제공하거나 외부 사용을 위해 public 메서드를 정의합니다. 때로는 특정 용도로 클래스 내에서만 사용되는 private 메서드를 정의하기도 합니다. 이것이 우리가 세부 사항을 숨기는 방법입니다.
예시:
/home/labex/project/encapsulationTest.java 파일에 다음 코드를 작성합니다.
class Person{
/*
* there are two member variables in Person
* they are private, so can't be accessed outside this class directly.
*/
private String name;
private int age;
// empty constructor
public Person(){
}
// constructor with two parameters
public Person(String name,int age){
this.name = name;
this.age = age;
}
// use this method to get name value
public String getName(){
return this.name;
}
// use this method to set name value
public void setName(String name){
this.name = name;
}
// use this method to get age value
public int getAge(){
return this.age;
}
// use this method to set age value
public void setAge(int age){
this.age = age;
}
}
public class encapsulationTest{
public static void main(String[] args){
Person p = new Person();
// we set a person's name and age using setXXX() methods
p.setName("Mike");
p.setAge(20);
// we get a person's name and age using getXXX() methods
System.out.println("Name: " + p.getName() + ", Age: " + p.getAge());
}
}
출력:
다음 명령을 사용하여 encapsulationTest.java 파일을 실행합니다.
javac /home/labex/project/encapsulationTest.java
java encapsulationTest
출력을 확인합니다.
Name: Mike, Age: 20
요약
캡슐화를 사용하면 object.XXX를 사용하여 객체 데이터 또는 속성에 직접 접근할 필요 없이, getXXX(), setXXX() 및 기타 메서드 형태의 표준 메서드를 사용하여 작업을 수행합니다. 일반 프로그래밍에서 다형성의 장점이 나타나지만, 지금은 다형성이 객체가 여러 형태를 취할 수 있도록 한다는 점을 기억하십시오.



