2013-02-11 4 views
1

다음과 같은 문제가 있습니다. 다음 두 클래스가 있다고 가정 해 봅시다. 자전거는 MountainBike입니다. MountainBike의 헤더에 있음 : public class MountainBike extends Bicycle. MountainBike 클래스는 자전거에없는 두 개의 필드를 추가합니다. 데이터베이스마다 하나씩 속성을 추가하기 때문에 생성자는 없지만 String 식별자와 값이 지정된 속성을 설정하는 함수는 없습니다. 모든 속성이 설정되지는 않았고 null 일 수도 있음을 알고 있습니다.하지만이 점이 좋습니다.더 구체적인 유형으로 캐스팅합니다.

이제 질문은 다음과 같습니다. 주어진 시점에서 나는 그것이 어떤 유형의 자전거인지 알고 있습니다. 그것은 분야 중 하나입니다. 내가하고 싶은 것은 다음과 같다.이 자전거 객체가 실제로 MountainBike라는 것을 알게되자 마자 MountainBike에 캐스팅하고 싶다 : MountainBike mb = (MountainBike) bicycle, 그러나 이것은 java.lang.ClassCastException 런타임에 결과를 가져온다 : 자전거는 할 수 없다. MountainBike에 캐스팅 해.

전 자전거를 인수로 사용하여 생성자를 사용하지 않고도 가능합니다. 어떻게해야합니까?

감사합니다.

if (bike instanceof MountainBike) { 
    MountainBike mb = (MountainBike) bike 
} else { 
    String msg = "Wrong bike, expected Mountainbike but was:" + bike.getClass(); 

    System.out.println(msg); 
    throw new IllegalArgumentException(msg); 
} 
+6

아니요. 작업중인 객체가 * 단지 '자전거'이므로 예외가 발생하는 경우 예외입니다. 작성한 후에는 오브젝트 유형을 변경할 수 없습니다. –

+0

감사합니다. 시도해 보겠습니다. 자전거에서 산악 자전거까지 모든 속성을 설정하는 효율적인 방법이 있습니까? –

+0

MountainBike를 처음부터 만들 수없는 이유가 있습니까? –

답변

6

처럼 존 소총 그것이 MountainBike이 아닌 경우 자신의 의견에, 당신이 캐스팅 할 수 없습니다 말했다 전에

헥터

경우
+0

Ok this to try this very much. 자전거에서 산악 자전거까지 모든 속성을 설정하는 효율적인 방법이 있습니까? –

+0

클래스는'getProperty' (또는'boolean'을위한'isProperty')와 같은 필드 규칙과'setProperty'와 같은 bean 규칙을 따릅니 까? – Brian

+0

불행히도 문자열 속성의 큰 시퀀스가 ​​아닙니다. –

1

당신은 캐스트가 검사를 실패 할 수 있습니다 의심 그냥 평범한 Bicycle입니다. 당신은 매개 변수로 Bicycle 소요 MountainBike의 생성자 생성됩니다 할 수있는 일 :

MountainBike mb = new MountainBike(Bicycle bicycle); 

당신은 어떤 이유에 대한 MountainBike 클래스를 수정할 수없는 경우

public MountainBike(Bicycle bicycle) { 
    // Copy bicycle's properties 
} 

를 대신 호출 팩토리 메소드를 만들 수도 있습니다.

public class MountainBikeFactory { 

    public static MountainBike createMountainBike(Bicycle bicycle) { 
     MountainBike mb = new MountainBike(); 
     // Copy bicycle's properties 
     return mb; 
    } 
} 

:

MountainBike mb = MountainBikeFactory.create(bicycle); 

편집 : 당신이 빌더 패턴을 시도 할 수처럼 당신이 질문에 주석으로 게시 된 정보를보고 한 후, 그것은 보인다. 빌더는 모든 속성을 변수로 포함하고 (예, 100+ 변수가 길어질 것임) 파일에서 속성을 발견 할 때 빌더에서 설정합니다. 그런 다음 마지막에 빌더의 build() 메소드를 호출 할 때 어떤 유형의 자전거를 만들고 다형성을 사용하여 속성 그룹 w.r.t를 처리 할 것인지를 결정하십시오. 어느 자전거를 만들었습니까? 예를 들어

는 :

public class BikeBuilder { 
    private String model; 
    private String wheelSize; 
    private String shocks; 
    private String racingHandleBarType; 

    // returns "this" so you can chain calls, common in builders, not necessary 
    public BikeBuilder setModel(String model) { 
     this.model = model; 
     return this; 
    } 

    // Other setters 

    public Bike build() { 
     Bike bike; 
     // Determine which kind of bike it is and create it 
     if (shocks != null) { 
      bike = new MountainBike(); 
      handleMountainBike((MountainBike) bike); 
     } else if (racingHandleBarType != null) { 
      bike = new RacingBike(); 
      handleRacingBike((RacingBike) bike); 
     } else { 
      bike = new Bike(); 
     } 
     handleCommonAttributes(bike); 
     return bike; 
    } 

    // All bikes have these attributes 
    private void handleCommonAttributes(Bike bike) { 
     bike.setModel(model); 
     bike.setWheelSize(wheelSize); 
    } 

    private void handleMountainBike(MountainBike bike) { 
     bike.setShocks(shocks); 
    } 

    private void handleRacingBike(RacingBike bike) { 
     bike.setRacingHandleBarType(racingHandleBarType); 
    } 
} 

이것은 당신이 즉석에서 자전거를 구축하고 대신 처음의 파일 읽기의 말에 유형을 결정할 수 있습니다. 일종의 컨테이너 역할을합니다. Bike을 확장하는 여러 유형이있는 경우 해당 유형을 새 방법으로 만들 수 있습니다. 적어도 당신을 시작할 것입니다.

2

MountainBike가 Bike를 확장하기 때문에 자전거를 MountainBike로 캐스팅 할 수 없습니다.예를 들면 다음과 같습니다.

Bike bike = new MountainBike(); 
MountainBike mb = (MountainBike) bike; //works 

Bike bike = new Bike(); 
MountainBike mb = (MountainBike) bike; //ClassCastException 
관련 문제