본문 바로가기
Java 배우기

Polymorphism 다형성

by 노화방지 Anti-aging Hairstyle 2016. 1. 5.
반응형


다형성(polymorphism)의 사전적 정의는 생물체나 종이 다양한 형태(forms) 또는 단계(stages)를 가질 수 있는 생물학 원리를 가리킵니다. 

이 원리는 자바 언어와 같은 객체-지향 프로그래밍 및 언어에도 적용될 수 있습니다.
클래스의 서브클래스는 서브클래스 만의 독특한 행위를 정의하면서 여전히 부모 클래스의 동일한 기능의 일부를 공유할 수 있습니다.

다형성은 클래스 Bicycle을 조금 수정하여 입증할 수 있습니다. 

예를 들어, 메소드 printDescription을 현재 인스턴스에 저장된 모든 데이터를 표시하는 클래스에 추가할 수 있습니다.

The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. This principle can also be applied to object-oriented programming and languages like the Java language. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class.

Polymorphism can be demonstrated with a minor modification to the Bicycle class. For example, a printDescription method could be added to the class that displays all the data currently stored in an instance.

public void printDescription(){
    System.out.println("\nBike is " + "in gear " + this.gear
        + " with a cadence of " + this.cadence +
        " and travelling at a speed of " + this.speed + ". ");
}


자바 언어에서 다형성 특징을 데모하기 위하여, MountainBikeRoadBike class로, Bicycle class를 확장하십시오.
MountainBikesuspension을 위한 필드를 추가하는데, 이 필드는 자전거가 front shock absorber인 Front를 갖고 있는지 여부를 가리키는 String 값입니다.
또는, 자전거는 front 및 back shock absorber인, 
Dual을 갖고 있습니다.

여기 업데이트된 클래스가 있습니다:

To demonstrate polymorphic features in the Java language, extend the Bicycle class with a MountainBike and a RoadBike class. For MountainBike, add a field for suspension, which is a String value that indicates if the bike has a front shock absorber, Front. Or, the bike has a front and back shock absorber, Dual.

Here is the updated class:

public class MountainBike extends Bicycle {
    private String suspension;

    public MountainBike(
               int startCadence,
               int startSpeed,
               int startGear,
               String suspensionType){
        super(startCadence,
              startSpeed,
              startGear);
        this.setSuspension(suspensionType);
    }

    public String getSuspension(){
      return this.suspension;
    }

    public void setSuspension(String suspensionType) {
        this.suspension = suspensionType;
    }

    public void printDescription() {
        super.printDescription();
        System.out.println("The " + "MountainBike has a" +
            getSuspension() + " suspension.");
    }
} 

오버라이드된 메소드 printDescription를 주목하십시오.
앞서 공급된 정보에 추가하여, suspension에 관한 추가 정보는 output에 포함됩니다.

다음으로, RoadBike class를 생성하십시오.
road or racing bikes는 skinny tires를 갖고 있기 때문에, tire width를 추적하기 위한 속성을 추가하십시오.
여기 RoadBike class가 있습니다:

Note the overridden printDescription method. In addition to the information provided before, additional data about the suspension is included to the output.

Next, create the RoadBike class. Because road or racing bikes have skinny tires, add an attribute to track the tire width. Here is the RoadBike class:

public class RoadBike extends Bicycle{
    // In millimeters (mm)
    private int tireWidth;

    public RoadBike(int startCadence,
                    int startSpeed,
                    int startGear,
                    int newTireWidth){
        super(startCadence,
              startSpeed,
              startGear);
        this.setTireWidth(newTireWidth);
    }

    public int getTireWidth(){
      return this.tireWidth;
    }

    public void setTireWidth(int newTireWidth){
        this.tireWidth = newTireWidth;
    }

    public void printDescription(){
        super.printDescription();
        System.out.println("The RoadBike" + " has " + getTireWidth() +
            " MM tires.");
    }
}


다시 한 번, printDescription method가 오버라이드 되었슴에 주목하십시오. 
지금, tire width에 관한 정보가 display 됩니다.

요약하면, 3개의 클래스가 있습니다: BicycleMountainBike, 및 RoadBike.
2개의 subclasses는 printDescription method를 오버라이드하고 unique한 정보를 프린트합니다.

여기 3개의 Bicycle variables을 생성하는 테스트 프로그램이 있습니다.
각 변수는 3개의 bicycle classes 중 하나에 할당됩니다.
그러면 각 변수가 프린트됩니다.

Note that once again, the printDescription method has been overridden. This time, information about the tire width is displayed.

To summarize, there are three classes: BicycleMountainBike, and RoadBike. The two subclasses override the printDescription method and print unique information.

Here is a test program that creates three Bicycle variables. Each variable is assigned to one of the three bicycle classes. Each variable is then printed.

public class TestBikes {
  public static void main(String[] args){
    Bicycle bike01, bike02, bike03;

    bike01 = new Bicycle(20, 10, 1);
    bike02 = new MountainBike(20, 10, 5, "Dual");
    bike03 = new RoadBike(40, 20, 8, 23);

    bike01.printDescription();
    bike02.printDescription();
    bike03.printDescription();
  }
}


The following is the output from the test program:

Bike is in gear 1 with a cadence of 20 and travelling at a speed of 10. 

Bike is in gear 5 with a cadence of 20 and travelling at a speed of 10. 
The MountainBike has a Dual suspension.

Bike is in gear 8 with a cadence of 40 and travelling at a speed of 20. 
The RoadBike has 23 MM tires.

The Java virtual machine (JVM) calls the appropriate method for the object that is referred to in each variable. It does not call the method that is defined by the variable's type. This behavior is referred to as virtual method invocation and demonstrates an aspect of the important polymorphism features in the Java language.



반응형

'Java 배우기' 카테고리의 다른 글

Using the Keyword super 키워드 super 사용하기  (0) 2016.01.05
Hiding Fields  (0) 2016.01.05
Overriding and Hiding Methods  (0) 2016.01.05
Multiple Inheritance of State, Implementation, and Type  (0) 2016.01.05
Inheritance 상속  (0) 2016.01.05

댓글